Possible bug?


#1


My update code is changing all of the values in the hash instead of just the movie I select. I cannot for the life of me figure out why. I even replaced my code with code copied from the example and it does it.

A Night at the Movies 8

Oops, try again. It looks like your 'puts' doesn't include spartacus: 4.


movies = {  #Movie title => Rating in stars
    spartacus: 4,
    sound_of_Music: 5,
    texas_Chainsaw_Massacre: 3
}

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

case choice
when "add"
  puts "Enter title:"
  title = gets.chomp
  if movies[title.to_sym] != nil
      puts "Already entered!"
  else
      puts "How would you rate the movie?"
      rating = gets.chomp
      movies[title.to_sym] = rating.to_i
  end
when "update"
  puts "Enter title:"
  title = gets.chomp
  if movies[title.to_sym] = nil
      puts "Error. Not in memory."
  else
      puts "New rating:"
      rating = gets.chomp
      movies[title.to_sym] = rating.to_i
      puts "#{title} has been updated with new rating of #{rating}."
  end
when "display"
  movies.each do |movie, title|
  puts "#{movie}: #{rating}"
  end
when "delete"
  puts "Deleted!"
else
  puts "Error!"
end


#2

What would you like to do?
display
spartacus:
sound_of_Music:
texas_Chainsaw_Massacre:

Your error message says you're not printing some particular piece of information, right? Are you? The output above doesn't contain what the error message mentions.


#3

It's giving me this error message:

Oops, try again. It looks like your 'puts' doesn't include spartacus: 4.

because it changed all of the values instead of just for Spartacus:

spartacus: 3
sound_of_Music: 3
texas_Chainsaw_Massacre: 3
{:spartacus=>4, :sound_of_Music=>5, :texas_Chainsaw_Massacre=>3}

#4

Oh I figured it out! In the "display" case I was using 'title' as a parameter when I should have used 'rating'


#5

Awesome work on managing to find the answer to your own question!

There's also another really subtle bug I saw inside the case statement for "update" when I was checking out your code

if movies[title.to_sym] = nil

This if statement will always evaluate to nil and be skipped over because movies[title.to_sym] is being set to nil with = instead of checking if it's equal to nil with ==, so it's possible to use update to add a new movie which doesn't already exist.

I found the best way to avoid these subtle bugs as a beginner was to take advantage of the fact that movies[title.to_sym] will be nil anyway if that movie doesn't exist. This means you don't have to explicitly do == nil checks anymore, which means less typing for us!


#6

All these bugs very rarely are. I've seen only a couple valid ones, and I'm glad that there hasn't been any more uncovered. :smile:


#7

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