What Does @@variable Mean in Ruby?

In Ruby, the double at-sign (@@) before a variable name (e.g. @@variable_name) is used to create a class variable. These variables are:

  • Static — i.e. only a single copy of the variable exists, regardless of however many instances of the class you create;
  • Globally scoped within the context of inheritance hierarchy — i.e. they're shared between a class and all its subclasses.

For example, consider the following class where a counter is incremented each time a new object is instantiated:

class Entity
  @@counter = 0

  def initialize
    @@counter += 1
    puts "There are #{@@counter} entities"

a = Entity.new
b = Entity.new
c = Entity.new

# output:
# "There are 1 entities"
# "There are 2 entities"
# "There are 3 entities"

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.

This post was published (and was last revised ) 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.