DEV Community

uberdwang
uberdwang

Posted on

1 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay