Reputation: 2130
@ - 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
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
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