If statement trouble

Hi guys,

I’m having some trouble with this exercise. My problem is regarding the feature where the hash is checked for a key that already exists. My if statement checking whether the hash already contains the movie title to be added isn’t working. I’ve tried multiple times by entering “The Dark Knight” when prompted for input, but every time I’ve done so my program seems to skip the conditional and prompt the user for the movie rating. Any help would be greatly appreciated! Thank you!

movies = {

TheDarkKnight: 4


puts “What would you like to do?:”

choice = gets.chomp

case choice

when “add”
puts “What would you like to add?:”
title = gets.chomp.to_sym
if movies[title] != nil
puts “Sorry, already in the hash”
puts “What is the rating of the movie? :”
rating = gets.chomp.to_i
movies[title] = rating

when “update”
puts “Updated!”
when “display”
puts “Movies!”
when “delete”
puts “Deleted!”
puts “Error!”

Please link to the exercise you are on. Thanks.

If memory serves me correctly, we don’t start with symbols, so try,

title = gets.chomp

without the .to_sym method attached.


I’ve linked the exercise above. I am not sure as to why what I have isn’t working though. I’ve created the hash using symbols and so when checking for a key, I should be able to reference the key within the hash using symbols, right?

1 Like

That could be written,

"The Dark Knight"
  title = gets.chomp
  if movies[title.to_sym].nil?
    puts "#{title} not in hash."

Thank you. What you posted makes sense. The only thing is that I’m supposed to use a symbol here in the hash. It would be great if I could make it work with the symbol.

"The Dark Knight": 4

Thank you! I think I got it to work. I wasn’t properly checking the nil condition. The method you suggested to check worked.

1 Like

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