@ - 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?
@a ||= 0is a commonly-used replacement forif not defined? @a.... The former is shorthand for@a = @a || 0, just asx += 1is forx = x + 1.