Does Ruby Have "Static" Variables?

In Ruby, when you declare a "class variable" (i.e. @@variable) it creates a static variable, where:

  • 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.

You should use class variables with caution as all subclasses inherit the same class variables from its superclass, which can lead to unexpected/confusing results.

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 Entity class.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.