meso_2600
meso_2600

Reputation: 2130

Instance variable in ruby acting like class variable

@ - instance variable @@ - class variable.

So instance variable value shouldn't be shared if no instance is created. But:

class Add

  def self.add(what)
    if not defined? @a
      @a = 0
    end
    @a += what
    puts @a.to_s
  end
end

Add.add(4)
Add.add(4)

Results in:

$ruby main.rb

4
8

Why?

Upvotes: 1

Views: 270

Answers (2)

kostja
kostja

Reputation: 61548

The @a you are referring to in the singleton method is an instance variable of Add's class.

You have effectively changed the scope of the method declaration to the eigenclass when you have defined the method as def self.add instead of def add.

Upvotes: 2

Marek Lipka
Marek Lipka

Reputation: 51151

Every class in Ruby is also an object, instance of Class class. So, your @a is simply instance variable of Add class.

Upvotes: 3

Related Questions