Write as
def test
puts var
self.var -= 1
puts var
self.var = var - 1
puts var
end
If you don't use self
, then Ruby will treat those var
as a local variables, rather then setter
method calls.
Just remember, in Ruby method call can never be made without receiver(implicit/explicit). Now if you write var = 1
, Ruby will treat as local variable assignment. But if you write self.var
, Ruby will parse it as a method call, and will try to call your setter method, if you defined. Also remember self.var = 1
is a syntactic sugar of self.var=(1)
.
There is more interesting discussion about the same, worth to read Private setters can be called by self, why not getters?
There is a recent bug was found regarding the private setters. Here is the Bug ticket, and it is now fixed too.