7. Update - only works when the new rating is 2 or 2.5


#1



when I update my movies with a new rating of 2 or 2.5, I pass the exercise; however, if the new rating is something other than 2 or 2.5, it shows the below error message:

Oops, try again. It looks like aladdin wasn't updated with a new rating of 2.

but the console still correctly shows "the rating of aladdin has been updated to 4"

can someone please tell me why? many thanks!!


movies={
    shutter_island:4,
    bridesmaids:3.5,
    zoolander:2,
    aladdin:3,
}
puts "Do you want to add/update/display/delete a movie?"
choice=gets.chomp
case choice
when "add"
puts "which movie would you like to add?"
title=gets.chomp
if movies[title.to_sym].nil?
    puts "what's the rating?"
    rating=gets.chomp
    movies[title.to_sym]=rating.to_i
puts "#{title} rated #{rating} has been added"
else
    puts "#{title} already exists, and its rating is #{rating}"
end
when "update"
puts "which movie would you like to update"
title=gets.chomp
if movies[title.to_sym].nil?
    puts "Sorry, #{title} cannot be found"
else
    puts "what's the new rating?"
    new_rating=gets.chomp
    movies[title.to_sym]=new_rating.to_i
    puts "the rating of #{title} has been updated to #{new_rating}"
end
when "display"
puts "Movies!"
when "delete"
puts "Deleted!"
else
    puts "Error!"
end


#2

The variable is not defined in the else so must be queried from the hash:

movies[title.to_sym]

#3

sorry, I still don't quite get it

I thought I already defined title, new_rating and movies[title.to_sym] in the update block, am I still missing something? why does the new number I input affect the end result? I thought if one number works then the others should also work.. and why does 'and its rating is #{rating}" matter here when it's in the add block?


#4

This happens in the if branch, but not the else.If the else branch is the first one encountered in the Run, the variable will be undefined and possibly raise an exception. movies[title] is the rating.


#5

I finally got it! thanks so much for the hint!!


#6

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