0

我必须更新电影标题及其相关评级并将其添加到现有哈希中。这是我到目前为止的代码:

movies = { 
Titanic:4, 
Bestman: 3,
Agora: 2
}

puts "What would you like to do?"
choice = gets.chomp

case movies
when "add"
    puts "What movie do you want to add?"
    title = gets.chomp
    puts "What's the rating of the movie?"
    rating = gets.chomp
    movies[title] = rating
    puts "#{title} has been added with a rating of #{rating}."

when "update"
puts "Updated!"
when "display"
puts "Movies!"
when "delete"
puts "Deleted!"
else 
    puts "Error!"
end

当我运行代码时,我收到此错误“看起来您没有添加到电影哈希中”

我知道错误位于以下几行之间:

case movies
when "add"
    puts "What movie do you want to add?"
    title = gets.chomp
    puts "What's the rating of the movie?"
    rating = gets.chomp
    movies[title] = rating
    puts "#{title} has been added with a rating of #{rating}."

我一直试图弄清楚,但到目前为止还没有弄清楚我做错了什么。

有没有其他方法可以添加到我的电影哈希中?我的 puts 代码让用户知道他/她的电影标题和评分已被添加有什么问题?

谢谢

编辑 正如 Some Guy 所指出的,将案例陈述从

case movies

case choice

解决了这个问题。

我需要学习/弄清楚为什么第二个有效但第一个无效。

4

2 回答 2

1

改变

case movies 

case choice  # because this is where your choice of what to do is being stored
于 2013-10-27T05:09:46.423 回答
0

如果仍不清楚,将 case 语句视为一系列 if/elsif 可能会有所帮助(存在差异,但对于这种情况它有效),因此:

case movies
when "add" # do stuff

类似于:

if movies == "add"
   # do stuff
end

希望这能让它更清楚。

于 2013-10-27T02:52:55.497 回答