首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ruby-意外的keyword_when,期待keyword_end

Ruby-意外的keyword_when,期待keyword_end
EN

Stack Overflow用户
提问于 2014-05-18 16:48:51
回答 2查看 2.7K关注 0票数 0

当在case语句中输入两个块时,我会收到两次此消息。找不到问题。

代码语言:javascript
复制
choice = gets.chomp.downcase!

case = choice

when "update"
puts "Enter the title of the movie to be updated."
title = gets.chomp.to_sym

    if movies[title] == nil
        puts "This movie is not in the system."
    else
        puts "Input the new rating."
        rating = gets.chomp.to_i
        movies[title] = rating
        retry if (rating < 0 || rating > 5)  
                    puts "This rating is invalid! Try again."
                end

    end

when "display"
movies.each do |title, rating|
    puts "#{title}: #{rating} / 5 stars"
    end
end

代码块进一步扩展到"when“的进一步实例,但为了简单起见,我决定截断它。如有必要,我可以提交完整的代码。这些错误具体如下:

代码语言:javascript
复制
    (ruby):57: syntax error, unexpected keyword_when, expecting keyword_end
     when "update"
     ^
    (ruby):72: syntax error, unexpected keyword_when, expecting $end
     when "display"
     ^
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-05-18 16:57:46

您所看到的错误是因为您的语法错误。在缩进代码时要非常小心,这样可以更容易地找到这类bug:

代码语言:javascript
复制
choice = gets.chomp.downcase!

case choice

when "update"
  puts "Enter the title of the movie to be updated."
  title = gets.chomp.to_sym

  if movies[title] == nil
    puts "This movie is not in the system."
  else
    puts "Input the new rating."
    rating = gets.chomp.to_i
    movies[title] = rating
    # retry if (rating < 0 || rating > 5)  
    puts "This rating is invalid! Try again."
  end

when "display"
  movies.each do |title, rating|
    puts "#{title}: #{rating} / 5 stars"
  end
end

end之前有一个额外的when "display"。我想这是为了关闭if (rating < 0 || rating > 5),但是由于它前面有一个语句,所以使它成为一个一行if语句

即使它是固定的,retry也被滥用了。由于不清楚您到底想做什么,所以我将其注释掉--我建议您阅读相关的文档,重新分级适当的retry语法,并相应地重新编写代码。

票数 3
EN

Stack Overflow用户

发布于 2014-05-18 16:58:03

我想这行case = choice应该是case choice

代码语言:javascript
复制
   choice = gets.chomp.downcase!

   case choice

   when "update"
    puts "Enter the title of the movie to be updated."
    title = gets.chomp.to_sym

    if movies[title] == nil
      puts "This movie is not in the system."
    else
      puts "Input the new rating."
      rating = gets.chomp.to_i
      movies[title] = rating
    if (rating < 0 || rating > 5)  
      puts "This rating is invalid! Try again."
    end

  when "display"
   movies.each do |title, rating|
    puts "#{title}: #{rating} / 5 stars"
  end
end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23724445

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档