Instance variable: self vs @

sarunw picture sarunw · Nov 7, 2009 · Viewed 39.1k times · Source

Here is some code:

class Person
  def initialize(age)
    @age = age
  end

  def age
    @age
  end

  def age_difference_with(other_person)
    (self.age - other_person.age).abs
  end

  protected :age
end

What I want to know is the difference between using @age and self.age in age_difference_with method.

Answer

Chuck picture Chuck · Nov 7, 2009

Writing @age directly accesses the instance variable @age. Writing self.age tells the object to send itself the message age, which will usually return the instance variable @age — but could do any number of other things depending on how the age method is implemented in a given subclass. For example, you might have a MiddleAgedSocialite class that always reports its age 10 years younger than it actually is. Or more practically, a PersistentPerson class might lazily read that data from a persistent store, cache all its persistent data in a hash.