2011-07-20 38 views
0

我對Ruby相當陌生,而且我正在構建一個基本上作爲交互式果園的程序,用戶將在其中輸入想要種植的樹的類型,然後給水,修剪,挑選和收穫樹。如何跟蹤Ruby中類之外的實例變量的更改?

我遇到的問題是當我試圖讓程序要求命令,直到樹死在某個高度發生。高度是在一個類內部的一個實例變量中定義的,我似乎無法弄清楚如何讓程序跟蹤該類以外的變量,以便它一直提示一個命令,直到達到某個值。

下面的代碼是代碼的開始和結束,但不是中間部分似乎工作正常。底部的每個命令都會工作一次,但程序結束。 任何幫助,將不勝感激。

class Orangetree 

def initialize name 
@name = name 
@height = 0 
@branches = 0 
@winter = false 
@orangesontree = 0 
@orangesinbasket = 0 
@timeOfyear = 0 
puts @name + 'Just Sprouted! What would you like to do with him?' 
end 

puts 'Welcome to the Orchard! What would you like to grow today?' 
reply = gets.chomp 
while reply != 'oranges' 
puts 'I am sorry, we do not have that kind of tree, try again' 
gets.chomp 
end 
oranges = Orangetree.new 'Woody ' 
while Orangetree |@height| <= 61 
    command = gets.chomp 
    if command == 'water' 
    puts oranges.rain 
    end 
    if command == 'pick' 
    puts oranges.pick 
    end 
    if command == 'prune' 
    puts oranges.prune 
    end 
    if command == 'harvest' 
    puts oranges.harvest 
    end 
end 

回答

0

您無法直接訪問對象的實例字段。使用getter方法。

attr_writer :height添加到您的班級將給你這個。

那麼你可以參考的高度外班有

while oranges.height <= 61