class A
def set(v)
@@v = v
end
def put
puts @@v
end
end
class B < A
end
class C < A
end
B.new.set 'b'
B.new.put # => b
C.new.set 'c'
C.new.put # => c
B.new.put # => c
Why? And how should I write this to have ‘b’ in last B.new.put?
Here is a nice article on the subject – Class and Instance Variables In Ruby.
Basically, what you can do is:
To understand it you should think about
Aas an instance ofClassclass (and that’s how it is in Ruby). But every object in Ruby has its own singleton class that stores object-specific stuff like methods defined on object itself:In that case
foois method defined only foraobject and not for every instance ofAclass. And another way to define method in object’s singleton class is like that:In the first code snippet we use that approach to define
class_varattribute accessor in the context of singleton class of ourAclass (it’s a bit tricky, so you need to think about it). As the result class itself hasclass_varvariable as well as its descendant classB. The difference is that every one of them has its ownclass_varvariable that do not interfere.