6. Error! Error! code 'works' but does not output correctly



No error message but the code does not respond how Ruby says it should. Instead, any movie name and rating are accepted into the hash, whether they are already in it or not.

movies = {
    ":Django Unchained" => 4.5
puts "What would you like to do?"
choice = gets.chomp

case choice
when "add"
puts "What movie would you like to add?"
title = gets.chomp.to_sym
title = title.to_sym
if movies[title.to_sym].nil?
movies[title.to_sym] = rating.to_i
puts "what rating would you give this movie 1-5?"
rating = gets.chomp
movies[title.to_sym] = rating.to_i
puts "#{title}, has been added with a rating of #{rating}."
puts "This movie already exists"

when "update"
puts "Updated!"
when "display"
puts "Movies!"
when "delete"
puts "Deleted!"
puts "Error!"


Make sure that you're testing for, and adding the same value for each respective entry.
For example, if you test for all caps but add downcased, then your test will never be satisfied because you'd never be adding something that satisfies it


I've made sure to have the exact name, it still accepts it no matter what. If I change the .nil? To = nil, it always declines it so I'm still not sure what to do to make this code work.


In the code you've posted you've initiated your hash with one key-value pair where the key is a string
But when you check for a key you're looking for a key that is a symbol, since there aren't any (because you didn't add any), it'll say it isn't there.

In other words, your mistake is to assume that they're the same instead of testing whether they are the same.

Also note that you're calling to_sym twice after having already converted it, you're doing: title.to_sym.to_sym.to_sym

Also, I suggest testing for key membership with has_key? instead of testing if the lookup result is nil, it makes no difference here but it's a more accurate description of what's being done

You can use a REPL (read eval print loop) to test your understanding of hash operations. If you have ruby installed locally then it comes with a command named irb, but there are also websites that provide the same thing.

For example, here starting with an empty hash, testing if a key is there (it's not), then adding that key, and finally testing for its membership again (this time it's there)

irb(main):001:0> entries = {}
=> {}
irb(main):002:0> entries.has_key?('bob eats dinner'.to_sym)
=> false
irb(main):003:0> entries['bob eats dinner'.to_sym] = 11
=> 11
irb(main):004:0> entries.has_key?('bob eats dinner'.to_sym)
=> true

..or just run very short regular programs where you test these things


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