Most Ruby code utilizes the implicit receiver, so programmers who are new to Ruby are often confused about when to use self. The practical answer is that self is used in two major ways:
1. To change the receiver.
Ordinarily the behavior of def inside a class or module is to create instance methods. Self can be used to define methods on the class instead.
class Foo
def bar
1
end
def self.bar
2
end
end
Foo.new.bar #=> 1
Foo.bar #=> 2
2. To disambiguate the receiver
When local variables may have the same name as a method an explicit receiver may be required to disambiguate.
Examples:
class Example
def foo
1
end
def bar
foo + 1
end
def baz(foo)
self.foo + foo # self.foo is the method, foo is the local variable
end
def qux
bar = 2
self.bar + bar # self.bar is the method, bar is the local variable
end
end
Example.new.foo #=> 1
Example.new.bar #=> 2
Example.new.baz(2) #=> 3
Example.new.qux #=> 4
The other common case requiring disambiguation involves methods that end in the equals sign. For instance:
class Example
def foo=(input)
@foo = input
end
def get_foo
@foo
end
def bar(input)
foo = input # will create a local variable
end
def baz(input)
self.foo = input # will call the method
end
end
e = Example.new
e.get_foo #=> nil
e.foo = 1
e.get_foo #=> 1
e.bar(2)
e.get_foo #=> 1
e.baz(2)
e.get_foo #=> 2