Вопрос

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

Это было полезно?

Решение

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

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top