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
belongs to only one specific class, whereas@@variable
is shared between a class and all its subclasses;@variable
is only available to class instance methods and not to class methods, while@@variable
is available to both, instance methods and class methods.
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.