I have to update and add a movie title and its associated rating to an existing hash. This is the code that i have so far:

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

When I run the code, I get this error "it looks like you didn't add to the movies hash"

I know the error lies somewhere between these lines:

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}."

I have been trying to figure it out but thus far have failed to figure out what I am doing wrong.

Is there an alternative way to add to my movies hash? And what is wrong with my puts code for letting the user know that his/her movie title and rating has been added?

Thank you

EDIT As pointed out by Some Guy, changing the case statement from

case movies

to

case choice

resolved the issue.

What I need to learn/figure out is why the 2nd works but the 1st does not.

有帮助吗?

解决方案 2

If it's still not clear, it may help to think of a case statement as a series of if/elsif (there are differences, but for this scenario it works), so:

case movies
when "add" # do stuff

is akin to:

if movies == "add"
   # do stuff
end

Hoping that makes it clearer.

其他提示

Change

case movies 

to

case choice  # because this is where your choice of what to do is being stored
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top