質問

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