Question

@ - 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?

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top