Search code examples
rubyself

What difference has adding the self keyword made?


When I started learning Ruby, I started with Michael Hartl's excellent Rails Tutorial. I just revisited the tutorial and noticed that portions of the example application code were modified. In the authentication chapter two methods were changed:

# SessionsHelper
def sign_in(user)
  ...
  self.current_user = user
end

def sign_out
  self.current_user = nil
  ...
end

Previously, the keyword self was omitted. But the app worked. So, if it ain't broke, why fix it? What value has self added and why is it used?

I understand that self defines class methods as opposed to instance methods. And in models, using self allows us to reference an object's property directly. But I can't tie the dots and see how it's being used in a helper. I've seen it in controllers before and I can't understand why we would want to use it there.


Solution

  • [Edit]

    It is likely that the original section of the tutorial was just plain wrong. Omitting the "self" receiver causes the methods to assign a value to the method local variable "current_user" with no other effect.

    My original answer below is incorrect and should be ignored (because writer methods foo=(x) cannot be called without a receiver, as can other methods).

    [Incorrect Original Answer Below]

    The reason for using the "self" receiver is likely for clarity.

    If "self" is omitted then, to the untrained eye, it looks like you are simply assigning the "user" variable to a new variable named "current_user" with no other effect. Experienced Rubyists know that if there is a method named "current_user" on the object instance then it will be called instead of just creating and assigning a new variable but this detail can easily be overlooked, especially if the method is inherited or otherwise not declared in the current class definition section.

    By using the "self" keyword explicitly you are clearly stating that you are calling a method on this object instance.