How do I track changes of an instance variable outside of the class in Ruby? -
i new ruby , building program works interactive orchard, user input type of tree want grow , give commands water, prune, pick , harvest tree.
the problem having when try have program ask commands until tree dies occurs @ height. height defined in instance variable inside class, , can't seem figure out how have program track variable outside of class, keeps prompting command until value achieved.
the below code start , end of code, not middle parts seem working fine. each of commands @ bottom work once, program ends. appreciated.
class orangetree def initialize name @name = name @height = 0 @branches = 0 @winter = false @orangesontree = 0 @orangesinbasket = 0 @timeofyear = 0 puts @name + 'just sprouted! him?' end puts 'welcome orchard! grow today?' reply = gets.chomp while reply != 'oranges' puts 'i sorry, not have 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
you cannot access object's instance field outside of class directly. use getter method.
adding attr_writer :height
class give you.
then can reference height outside class
while oranges.height <= 61
Comments
Post a Comment