Reputation: 2314
I'm trying to update a movie list called movies
. I want to use include?
to figure out whether a program is trying to update a movie already on the list or if the movie is not currently included in movies
.
Here's the object movies
movies = {
:"Mean Girls" => 4,
Avatar: 2,
:"Spiderman 2" => 3,
Shrek: 4
}
The update is under a case statement.
when "update"
puts "Type in the movie you'd like to update"
title = gets.chomp
if movies[title.to_sym].include?(title.to_sym)
puts "Type in a new rating of 1-4 for that movie"
rating = gets.chomp
movies[title.to_sym] = rating.to_i
else
puts "That movie is not currently in our movie list"
end
When I type in the title of the movie I want to update I get the error message:
undefined method `include?' for 4:Fixnum
What does that mean? Is it not possible to use the include?
method here?
I also tried removing title.to_sym
after include?
but that didn't work either.
Here's all my code
movies = {
:"Mean Girls" => 4,
Avatar: 2,
:"Spiderman 2" => 3,
Shrek: 4
}
puts "Do you want to add a movie, update a movie ranking, display all movies and rankings or delete a movie?"
choice = gets.chomp
case choice
when "add"
puts "Type in the movie you'd like to add"
title = gets.chomp.to_sym
if movies[title].nil?
puts "Type in a rating of 1-4 for that movie"
rating = gets.chomp.to_i
movies[title] = rating
else
puts "That movie is already in our list. Run the program and select update to change its rating"
end
when "update"
puts "Type in the movie you'd like to update"
title = gets.chomp
if movies[title.to_sym].include?(title.to_sym)
puts "Type in a new rating of 1-4 for that movie"
rating = gets.chomp
movies[title.to_sym] = rating.to_i
else
puts "That movie is not currently in our movie list"
end
when "display"
puts "Movies!"
when "delete"
puts "Deleted!"
else
puts "Error!"
end
Upvotes: 0
Views: 55
Reputation: 160551
Here's the problem:
movies = {
:"Mean Girls" => 4,
Avatar: 2,
:"Spiderman 2" => 3,
Shrek: 4
}
movies['Avatar'.to_sym] # => 2
movies['Avatar'.to_sym].include?('Avatar'.to_sym) # =>
# ~> NoMethodError
# ~> undefined method `include?' for 2:Fixnum
If you want to see if a particular title is a key in your hash you can do it like this:
title = 'Avatar'
movies.key?(title.to_sym) # => true
title = 'Blade Runner'
movies.key?(title.to_sym) # => false
Knowing that you can a sensible conditional test using something like:
if movies.key?(title.to_sym)
If you're always going to have integers for the values, and never false
or nil
, then you could shorten it to:
if movies[title.to_sym]
Upvotes: 2
Reputation: 108
Since movies is a hash containing the movie titles as keys, with whatever numbers you've specified as values, that is why
movies[title.to_sym]
gives you the Fixnum 4, and Fixnum does not have an "include?" method.
You mean to say
movies.include?(title.to_sym)
which will return true/false if your hash has that title as a key.
Upvotes: 2