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

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:

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)"

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.