2011-07-20 41 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