Problem
If I do this:
1 2 |
|
there is always the doubt whether I’m accessing a local variable, or calling methods foo
and foo=
.
TL;DR
When you want to call an instance’s own methods, use self
:
1 2 |
|
Example 1
1 2 3 4 5 6 7 8 9 |
|
Here, we define a method, and then make an assignment. As we assign to a bareword, Ruby creates a new local variable.
As soon as a value is assigned to the local variable, the method no longer gets called.
Example 2
But, what if we also have an assignment method?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Adding the method example2=
does not change things. When we assign to a bareword, Ruby takes it as assignment to a local variable.
Example with a Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
|
method2
is the problem case. bar
is assigned to, creating a local variable, so subsequent calls to bar
return 99.
method3
disambiguates by explicitly calling the bar
method on self
.
The Cause
There are two things going on here:
- bareword assignment creates local variables,
- local variables mask methods of the same name.
Refactoring Might Break Code
One solution is to use self.method
only in cases where local variables mask methods. The problem with this approach is that code may be altered, introducing local variables, and so altering the behaviour of following code:
Original Code
1 2 3 4 5 6 7 8 9 10 11 |
|
Modified Code
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Solution
The best solution is to always call instance methods on self
.