我使用包含所有类别名称,获奖者和被提名者的文本文件创建了一个包含奥斯卡信息的对象数组(获奖者也出现在被提名者列表中)。我现在想要能够询问用户。您想知道哪个类别的获胜者?一旦提出问题,它就会回答问题。我只能让它在数组的最后一个对象上工作(最佳视觉效果返回重力)。有人可以解释为什么会这样吗?
class AwardCategory
attr_accessor :winner, :name, :nominees
def initialize(name)
@name = name
@nominees = []
end
end
class Nominee
attr_accessor :name
def initialize(name)
@name = name
end
end
file = File.open('oscar_noms.txt', 'r')
oscars = []
begin
while true do
award_category = AwardCategory.new(file.readline.downcase)
award_category.winner = file.readline.downcase
nominee = Nominee.new(file.readline.downcase)
award_category.nominees << nominee
next_nominee = Nominee.new(file.readline.downcase)
until next_nominee.name == "\n"
award_category.nominees << next_nominee
next_nominee = Nominee.new(file.readline.downcase)
end
oscars << award_category
end
rescue EOFError => e
puts 'rescued'
end
#puts oscars.inspect
#Read input here
puts "What category do you want to know the winner for?"
answer = gets
oscars.each
if answer.downcase == award_category.name
puts award_category.winner
else
puts "That is not a category"
end
答案 0 :(得分:0)
那段代码
puts "What category do you want to know the winner for?"
answer = gets
oscars.each
if answer.downcase == award_category.name
puts award_category.winner
else
puts "That is not a category"
end
现在有正确的缩进
puts "What category do you want to know the winner for?"
answer = gets
oscars.each
if answer.downcase == award_category.name
puts award_category.winner
else
puts "That is not a category"
end
请注意,oscars.each
下面的部分没有缩进,因为each
需要一个do
/ end
块,它将为每个元素执行一次。你可能想要的是这个
puts "What category do you want to know the winner for?"
answer = gets
oscars.each do |award_category|
if answer.downcase == award_category.name
puts award_category.winner
else
puts "That is not a category"
end
end
虽然我建议您不要使用其他内容,因为对于每个不匹配的答案,您都会收到"That is not a category"
消息。此外,您应该使用gets.chomp
从用户输入中删除换行符,并在downcase
循环之外执行each
。最后一点,你的一些变量命名不佳。例如,为什么奖项类别列表应该命名为oscars
?它应该是award_categories
。