What's the Difference Between @variable and @@variable in Ruby?

@variable vs. @@variable

In Ruby, variables with a single at-sign (i.e. @variable) are class instance variables while variables with double at-sign (i.e. @@variable) are class variables. This means that:

  • Each class object instance has a separate copy of @variable, whereas only a single copy of @@variable exists regardless of however many instances of the class exist;
  • @variable is only directly accessible within the class methods of the class it's defined in, whereas @@variable is shared between a class and all its subclasses and ancestors.

For example:

class Person
  @@total = 0

  def initialize(name)
    @name = name
    @@total += 1
  end

  def self.total
    @@total
  end

  attr_accessor :name
end

person1 = Person.new("Bob")
person2 = Person.new("John")

puts "#{person1.name} & #{person2.name} (#{Person.total})"

# output: "Bob & John (2)"

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