Update case statement not recognizing keys in movies hash


#1




So I am stuck at the part where we are asked to replace the puts statement "Updated!" with "What movie would you like to update?"

I tried to update a movie in the movies hash, but for some reason my code runs as if the condition movies[title] == nil is true and outputs the message

"Sorry, this movie does not exist in the system."

I added a print case statement to make sure that I do have the correct key/value pairs in my hash, which I do. I even made sure the casing of my input was spelled exactly like the keys are in the movies hash, but it still outputs the same message.

Anyone see why this is?

movies = { Speed: 10 , Gladiator: 8 , GoneGirl: 8 } 
puts "What would you like to do?"
choice = gets.chomp 
case choice 
when "print"
    movies.each do |name, rating|
        puts "#{name}: #{rating}"
    end
when "add"
    puts "What is the name of the movie would you like to add?"
    title = gets.chomp.to_sym
    if movies[title.to_sym] == nil 
        puts "What rating would you like to give \"#{title}\"?"
        rating = gets.chomp.to_i
        movies[title] = rating 
        puts "Congrats, #{title} has just been added with a rating of #{rating}!"
    else
        puts "Sorry, this movie already exists!"
    end    
when "update" 
    puts "What movie would you like to update?"
    title = gets.chomp
    if movies[title] == nil 
        puts "Sorry, this movie does not exist in the system."
    else 
        puts "What would you like to rate this movie?" 
        rating = gets.chomp.to_i
        movies[title] = rating
    end
end


#2

This will only return True is movies[title] is actually nil. Use,

if movies[title.to_sym].nil?

Same applies in the add case.

The instructions are to include a display case, not a print case.


#3

ahh I see, so because I did not the make the variable title a symbol by including the .to_sym after gets.chomp it did not recognize the title in the movie hash since the title in update was a string from the user input and the title from the movies hash is a symbol.

Thank you for clearing that up!

Also I had forgotten a display case was made and had just whipped up a print statement real quick haha my mistake


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.