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


#1



https://www.codecademy.com/courses/ruby-beginner-en-0i8v1/0/7?curriculum_id=5059f8619189a5000201fbcb#


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
choice.downcase!

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}."
        else
            puts "Error! Movie already in database!"
    end
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!"
        else
            puts "Enter new rating:"
            rating = gets.chomp
            movies[title.intern] = rating.to_i
    end
when "display"
    puts "Movies!"
when "delete"
    puts "Deleted!"
else
    puts "Error!"
end


#2

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.


#3

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