根据Ruby中对象数组中的用户输入输出正确的对象属性



我使用一个文本文件创建了一个对象数组,其中包含有关奥斯卡的信息,该文件包含所有类别名称、获奖者和被提名人(获奖者也出现在被提名人列表中)。我现在希望能够询问用户。你想知道哪一类的获胜者?一旦问题被提出,它就会返回答案。我只能让它在数组的最后一个对象上工作(最佳视觉效果返回重力)。有人能解释一下为什么会这样吗?

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

这段代码

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

虽然我建议你离开else,因为你会得到消息"That is not a category"的每一个不匹配的答案。此外,您应该使用gets.chomp从用户输入中删除换行符,并在each循环之外执行downcase。最后要说明的是,有些变量的命名很糟糕。例如,为什么一个奖项类别列表要命名为oscars ?应该改成award_categories

最新更新