Over a million developers have joined DZone.

Class Variables Vs Class Instance Variables

·
A class variable (@@variable) is referenced within the context of any object instantiated from the class, wheres a class instance variable (self.class.variable) is referenced from the class itself.

class variable example copied from Class: Module [ruby-doc.org]

class One
  @@var1 = 1
end
class Two < One
  @@var2 = 2
end
One.class_variables   #=> ["@@var1"]
Two.class_variables   #=> ["@@var2", "@@var1"]


class instance variable example copied from Ruby Programming/Syntax/Classes - Wikibooks ... [wikibooks.org]

class Employee
  class << self; attr_accessor :instances; end
  def store
    self.class.instances ||= []
    self.class.instances << self
  end
  def initialize name
    @name = name
  end
end
class Overhead < Employee; end
class Programmer < Employee; end
Overhead.new('Martin').store
Overhead.new('Roy').store
Programmer.new('Erik').store
puts Overhead.instances.size    # => 2
puts Programmer.instances.size  # => 1
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}