2014-03-27 60 views
0

我創建了一個包含奧斯卡信息的對象數組,使用帶有所有類別名稱,獲獎者和提名者的文本文件(獲獎者出現在提名名單中作爲好)。我現在想要問一個用戶。你想知道哪個類別的獲勝者?一旦問題被問到,它會返回答案。我只能讓它在數組的最後一個對象上工作(最好的視覺效果會返回重力)。有人可以解釋爲什麼會這樣嗎?根據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 

回答

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從用戶輸入中刪除換行符,並在each循環之外執行downcase。作爲最後一點,你的一些變量名稱很差。例如,爲什麼應將獎項類別列表命名爲oscars?應該是award_categories

+0

我很感激幫助!該陣列被稱爲奧斯卡獎,因爲它擁有提名者,獲勝者和類別。我想最終設定它來回答有關奧斯卡的任何問題。 –

相關問題