hello,
i have a question according ‘self’. I have setup a small simple scenario
to simulate the problem.
This following small program works fine …
class User
def set_foo
self.x = ‘1’
end
def get_foo
x
end
def x=(val) @x = val
end
def x @x
end
end
u = User.new
u.set_foo
puts(u.x)
puts(u.get_foo)
when i now remove the ‘self’ within the method ‘set_foo’ it does not set
the values any more.
class User
def set_foo
x = ‘1’
end
def get_foo
x
end
def x=(val) @x = val
end
def x @x
end
end
u = User.new
u.set_foo
puts(u.x)
puts(u.get_foo)
so my 1st question is: why doesnt the ‘set_foo’ method calls the ‘x’
method if i remove the self?
THE INTERESTING THING: ‘get_foo’ works with ‘x’ and ‘self.x’
and the 2nd question: when should i use self now and when not and why is
there this strange behavoir?
Here’s a small example to illustrate Jari’s point:
class User
attr_accessor :x
def foo
self.x = 1
puts x # => 1
x = 2
puts x # => 2
puts self.x # => 1
end
end
User.new.foo
Any assignment without an explicit receiver will set a local
variable. You also need to use self if the method you’re calling is
shadowed by a local variable with the same name, as in my example
above. Finally, you must use self if the method you’re calling is a
reserved word, such as self.class.
Page 86 of the Pickaxe book (Programming Ruby) talks about this.