【发布时间】:2014-05-05 17:16:32
【问题描述】:
我使用包含所有类别名称、获奖者和提名者的文本文件创建了一个对象数组,其中包含有关奥斯卡奖的信息(获奖者也出现在提名者列表中)。我现在希望能够询问用户。您想知道哪个类别的获胜者?一旦提出问题,它将返回答案。我只能让它在数组的最后一个对象上工作(最佳视觉效果返回重力)。有人可以解释为什么会这样吗?
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
【问题讨论】: