Search code examples
rubyself

Why is `self` needed inside this instance method?


Going through Well Grounded Rubyist.

class Car
  @@cars = {}
  attr_reader :make
  def make_mates
    @@cars[self.make]
  end
  ...
end

Why do we need self in the make_mates instance method? When I run the code without self, it works the same.


Solution

  • You don't need it in that case.

    You only need to refer to an attribute with self if you're assigning to it, to distinguish it from assigning to a local.