Friday, July 25, 2014

Why we have to apply self to call setter method for ruby class object

class Test
  attr_accessor :name

  def set_name
    name = "some name"
  end
end

obj = Test.new
obj.set_name
obj.name  #=> nil

Why? i am calling the setter method which is already defined by attr_accessor from the method. Here the preferences comes into picture. Inside a method local variable is given more preference then to call the method, Ruby interpreter treats name as local variable. If you apply self before the method name you are specifying the interpreter to call the method.

class Test
  attr_accessor :name

  def set_name
    self.name = "some name"
  end
end

obj = Test.new
obj.set_name
obj.name #=> "some name"