Gwater17 Gwater17 - 7 months ago 9
Ruby Question

How to get include? to work with my code

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

Answer

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.

Comments