When to use `self.foo` instead of `foo` in Ruby methods
It is idiomatic to prefer to omit
self.
when invoking methods; it is generally never needed.-
You must use
self.foo = xxx
when calling a setter method, instead offoo = xxx
, so that Ruby realizes that you are not trying create a new local variable.- Similarly, in the unlikely event that you have an existing local variable
do_something
with the same name as a method, you must useself.do_something
to invoke the method, as justdo_something
will end up reading the variable.
- Similarly, in the unlikely event that you have an existing local variable
You cannot use
self.foo(...)
to call a private method; you must instead call justfoo(...)
.
If you omit self
Ruby will first look for local variables with that name, then for an instance method. It's not idiomatic to write self.
. In any case, you have to write self.something = value
on assignations.
Note that you cannot use self
when calling private methods (no problem with protected methods):
class A
def foo; self.bar; end
private
def bar; "bar"; end
end
A.new.foo
# private method `bar' called for #<A:0x7f49193584f0> (NoMethodError)