如何获得包含?使用我的代码

How to get include? to work with my code

我正在尝试更新名为 movies 的电影列表。我想使用 include? 来确定某个程序是否正在尝试更新列表中已有的电影,或者该电影当前是否未包含在 movies.

这是 object 部电影

movies = {
:"Mean Girls" => 4,
Avatar: 2,
:"Spiderman 2" => 3,
Shrek: 4
}

更新是在 case 语句下进行的。

  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

当我输入要更新的电影的标题时,我收到错误消息:

undefined method `include?' for 4:Fixnum

这是什么意思?这里不能用include?的方法吗?

我也尝试在 include? 之后删除 title.to_sym,但这也没有用。

这是我所有的代码

    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

由于 movies 是一个包含电影标题作为键的散列,以及您指定的任何数字作为值,这就是为什么

movies[title.to_sym]

为您提供 Fixnum 4,而 Fixnum 没有 "include?" 方法。

你的意思是说

movies.include?(title.to_sym)

如果您的散列具有该标题作为键,这将 return true/false。

这是问题所在:

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

如果您想查看特定标题是否是哈希中的键,您可以这样做:

title = 'Avatar'
movies.key?(title.to_sym) # => true

title = 'Blade Runner'
movies.key?(title.to_sym) # => false

知道您可以使用类似以下内容的合理条件测试:

if movies.key?(title.to_sym)

如果您总是将整数作为值,而不是 falsenil,那么您可以将其缩短为:

if movies[title.to_sym]