无法显示其他条件

时间:2015-12-03 17:05:00

标签: ruby

我正在通过一个codeacademy项目,我无法显示某个条件。这是我的代码。

当我选择add并选择要添加的电影时,我希望它让我知道我输入的电影是否已存在于散列中。当我输入已经存在于哈希中的电影时,它会询问我的评级。我相信我在正确的地方有else陈述,但它似乎没有起作用。

更新:我更改了这两行代码(删除.to_sym)

title = title
if movies[title].nil?

它不允许我输入重复项。

现在当我选择“添加”然后尝试添加“Memento”时,我收到错误消息 “#{title}已经存在。它的评级为#{rating}!” #{rating}产生1的整数(由于整数值为4,因此没有意义。)

movies = {
"Memento" => 4,
"Inception" => 3,
"The Prestige" => 2,
"Interstellar" => 1
}

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

case choice

# ADD
when "add" 
puts "What would you like to add?"
title = gets.chomp
title = title
if movies[title].nil?
puts "What its rating? (enter 1-4)"
rating = gets.chomp
movies[title.to_sym] = rating.to_i
puts "#{title} has been added with a rating of #{rating}"
else puts "#{title} already exists. Its rating is #{rating}!"
end

# UPDATE
when "update" 
puts "Updated!"

# DISPLAY
when "display" 
puts "Movies!"

# DELETE
when "delete" 
puts "Deleted!"

# ERROR
else 
puts "Error!"

2 个答案:

答案 0 :(得分:0)

由于title是一个字符串,因此您无需将其转换为符号。然后,您可以使用Hash::include?查看密钥是否存在。

# ADD
when "add" 
  puts "What would you like to add?"
  title = gets.chomp
  # title = title.to_sym                # delete this line since the hash keys are strings
  if !movies.include? title             # use Hash::include? to see if key exists
    puts "What its rating? (enter 1-4)"
    rating = gets.chomp
    ...
  else
    puts "Movie already exists. Its rating is #{movies[title]}!"   # remove .to_sym
end

答案 1 :(得分:0)

当您删除to_sym调用时,您没有删除所有调用:

Its rating is #{rating}!"

rating = movies[title]
puts "#{title} already exists. Its rating is #{rating}!"

未引用它引用变量评级的电影评级。还没有确定。

else块应为

{{1}}