If statement trouble


#1

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”
else
puts “What is the rating of the movie? :”
rating = gets.chomp.to_i
movies[title] = rating
end

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


#2

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.


#3

https://www.codecademy.com/courses/learn-ruby/lessons/a-night-at-the-movies/exercises/error-error?action=resume_content_item

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?


#4

That could be written,

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

#5

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.


#6
"The Dark Knight": 4

#7

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


#8

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