Instance variables @ vs self

uberdwang

uberdwang

Posted on September 27, 2019

Instance variables @ vs self

In a class sometimes I see attributes with @ or a self. At a quick glance they seem to do the same thing.

class MyClass
  def initialize(arg)
    @my_attribute = arg
  end

  def my_attribute
    @my_attribute
  end

  def output_attribute
    puts @my_attribute
    puts self.my_attribute
  end
end

my_instance = MyClass.new("testing123")
my_instance.output_attribute

Output:

testing123
testing123

From what I learned @ returns the instance variable, and self calls the getter method to return @. So I can see the difference if I modify the variable in the accessor method. For example for my FakeId class, self.age adds 10 years to the @age and returns that value.

class FakeId
  def initialize(arg)
    @age = arg
  end

  def age
    @age + 10
  end

  def output_age
    puts "Real age: #{@age}"
    puts "Fake ID age: #{self.age}"
  end
end

fake_id = FakeId.new(15)
fake_id.output_age

Output:

Real age: 15
Fake ID age: 25
💖 💪 🙅 🚩
uberdwang
uberdwang

Posted on September 27, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related