Search code examples
rubyclassinstance-variables

RUBY instance variable is reinitialized when calling another method


why is the instance variable @my_instance return nil even thought it's been set to 0 in the my_method ?

attr_accessor should let me write and read the instance, right ?

what would be the right way to do something like this ?

thank You.

class Myclass

  attr_accessor :my_instance

  def initialize
    @my_instance
  end 

  def called_method
    puts "this is my instance value #{my_instance} "
  end 

  def my_method
    my_instance = 0
    puts "i set my instance to be #{my_instance}"
    called_method
  end 

end 

a = Myclass.new

a.my_method

called_method return nil when i expect 0


Solution

  • what would be the right way to do something like this ?

    my_instance = 0
    

    This creates a local variable instead of calling your setter. Give ruby a hint that you want to call the method:

    self.my_instance = 0
    

    Or you can set the instance variable directly:

    @my_instance = 0