Stop using self when you don’t need to. In almost all cases it’s redundant.
I’m often the final reviewer of code before it gets merged with a mainline branch, or deployed for QA, or what-not. I keep on correcting the same “mistake”, so let me make this Rubyism regarding self a little clearer.
If you don’t have a local variable named “id”, then there’s no difference at all between:
Even though I’m picking “id” as the example, this applies to any method. It’s just that I see this done frequently with “id” inside models, seemingly because some think the “id” of ActiveRecord is special in some way. It’s not. It’s just a method in your AR object. You don’t need to prefix it with self.
I want to stress the generality of this, so let me repeat with “foo”.
If you don’t have a local variable named “foo”, then there’s no different at all between:
Every method in Ruby has self as the implied receiver.
The primary case where it actually matters to explicitly prefix “self.” to something is when that something is on the left hand side of an assignment. This is to differentiate between invoking a method whose name ends with ‘=’ and assigning a local variable of the same name. The canonical example of this is in the PickAxe book (“Programming Ruby”, 2nd Ed), page 86.
Additionally, when a method on the current object and a local variable have the same name, say “bar”, one can use “self.bar” to call the method and simply “bar” to reference the local variable.
Finally, if you need to reference the method “class”, define for all objects, you must use “self.class” because class is a reserved word in Ruby.
In no other cases can I think of a reason why you would put “self.” in front of a reference. So save yourself the typing and stop it please. :)
Anyone know of additional corner cases I missed?