7. Code does not work properly but let's me pass anyway?



When I try to add a new movie, it incorrectly tells me that the movie is already in the hash. But when I try to update a film not in the hash, it acts as though it were already in the hash and I am allowed to continue to the next lesson. I am extremely confused and frustrated. I saw other posts about this problem but I was not able to understand the answers.

movies = {
    Nightcrawler: 4,

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

case choice
when "add"
    puts "Input movie title:"
    title = gets.chomp
    puts "Input movie rating:"
    rating = gets.chomp
        if movies[title.to_sym] = nil
            movies[title.intern] = rating.to_i
            puts "#{title}: #{rating}."
            puts "Error! Movie already in database!"
when "update"
    puts "Input the title of the film you wish to update:"
    title = gets.chomp
        if movies[title.intern] = nil
            puts "Movie not yet in database!"
            puts "Enter new rating:"
            rating = gets.chomp
            movies[title.intern] = rating.to_i
when "display"
    puts "Movies!"
when "delete"
    puts "Deleted!"
    puts "Error!"


You're using the following expression as a condition:

movies[title.to_sym] = nil

It doesn't test if the hash already has a hash and it doesn't compare a value in the hash to nil.

What it does do is assign nil as the value that a key corresponds to. Similar to:

my_hash['hi'] = 3

And then you use the result of that expression, in this case always nil, which is falsy.

A better way of testing whether a hash has a key is to use the has_key? method, as there may be keys having nil as its corresponding value, or there may be a default value that isn't nil so you could get incorrect results.


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