开发者

How do I track changes of an instance variable outside of the class in Ruby?

开发者 https://www.devze.com 2023-03-22 00:36 出处:网络
I am fairly new to Ruby and I am building a program that basically works as an interactive orchard, where the user will input what type of tree they want to grow and then give commands to water, prune

I am fairly new to Ruby and I am building a program that basically works as an interactive orchard, where the user will input what type of tree they want to grow and then give commands to water, prune, pick and harvest the tree.

The problem I am having is when I try to have the program ask for commands until the tree dies which occurs at a certain height. The height is defined in an instance v开发者_如何学运维ariable inside a class, and I can't seem to figure out how to have the program track that variable outside of the class, so that it keeps prompting for a command until a certain value is achieved.

The below code is the start and end of the code, but not the middle parts which seem to be working fine. Each of the commands at the bottom work once, but then the program ends. Any help would be appreciated.

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  


You cannot access an object's instance field outside of its class directly. Use a getter method.

Adding attr_writer :height to your class will give this to you.

Then you can reference the height outside the class with

while oranges.height <= 61
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号