What Does @@variable Mean in Ruby?

Learn what the double at-sign (@@) before a variable name means 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"
  end
end

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.


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