- Only one copy of this variable exists across all instances of the class, and;
- This variable is shared between the class and all its subclasses.
For example, consider the following class where a static
counter is incremented each time a new object is instantiated:
class Entity @@counter = 0 def initialize @@counter += 1 end def counter @@counter end end a = Entity.new b = Entity.new c = Entity.new puts a.counter #=> 3 puts b.counter #=> 3 puts c.counter #=> 3
As you can see from the example above, all instances of the class return the same value from
counter() method, because
@@counter is a class variable that's shared across all instances of the
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.