Search code examples
rubyinstance-variables

How can I update the value of an instance variable?


I have a class OrangeTree and a function OneYearPasses. This function is supposed to increment the age and height of a tree by one.

class OrangeTree
  def initialize(height, age)
    @height = height
    @age = age
  end

  def age
    @age
  end

  def height
    @height
  end

  def OrangeHeight
    puts "This Orange tree is #{height} unit  tall"
  end

  def OneYearPasses
    age =+ 1
    height =+ 1
    puts "This Orange tree is now #{age} years old and its height is      now #{height}"
  end
end

FirstOrangeTree = OrangeTree.new(0,0)

When I try to increment them, it doesn't save the new values:

orangeOne =  FirstOrangeTree.OneYearPasses
# >> This Orange tree is now 1 years old and its height is now 1
orangeOne = FirstOrangeTree.OneYearPasses
# >> This Orange tree is now 1 years old and its height is now 1

I guess it only returns a new copy.

What am I doing wrong?


Solution

  • You have two issues there. The first is to increment anything one should use:

    var = var + 1
    

    that might be shortened to

    var += 1
    

    not to

    var =+ 1
    

    The latter is simply read as

    var = +1
    

    Another issue is you are messing getters, instance variables and [absent in your code] setters. Your age method reads a value of the variable. To set it, one should either set the value of the instance variable:

    @age += 1
    

    or declare a setter:

    def age=(value)
      @age = value
    end
    

    and use it as shown below:

    self.age += 1
    

    self above is mandatory because otherwise, ruby interpreter will create a local variable instead of calling the setter method.