Search code examples
rubyself

How to use the Ruby "self" keyword


I'm having trouble understanding the self keyword.

I understand how it's used to distinguish between instance methods and class methods but what about when it's used from inside a method?

Something like:

def self.name
  self.name = "TEXT"
end

or

def name2
  self.name = "TEXT2"
end

or

class Array
  def iterate!(&code)
    self.each_with_index do |n, i|
      self[i] = code.call(n)
    end
  end
end

Solution

  • Usually, self as a receiver can be omitted, and in such cases, it is usually preferable to do so. However, there are a few cases when omitting self make the code mean something else.

    • One such case is, as in your example self.name = ..., using a setter method. Ruby's syntax is ambiguous between method and variable call, and when something that can be interpreted either as a variable or a method is followed by =, its interpretation as a local variable assignment has priority.

    • Another case is when you want to call the method class. There is also the keyword class, and interpretation of class as the keyword has priority over it as the method.

    • Still another case is when you want to use the method []. This notation is also used for array literal, and interpretation of it as an array has priority over it as a method.

    In each of these cases, you have to make the expression be unamgiguously a method call. One way is to explicitly write the receiver even when it is self. The other way is to write () after the method.

    Regarding your example self.each_with_index ..., the self can be omitted, and not doing so is not a recommended practice.