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

オブジェクトのインスタンスフィールドに直接アクセスすることはできません。ゲッターメソッドを使用します。

あなたのクラスにattr_writer :heightを追加すると、これが表示されます。

次にあなたが

while oranges.height <= 61 
とクラス外で高さを参照することができます
関連する問題