DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Class Variables Vs Class Instance Variables

05.28.2010
| 5098 views |
  • submit to reddit
        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 <a href="http://ruby-doc.org/core/classes/Module.html#M001694">Class: Module</a> [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 <a href="http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Classes">Ruby Programming/Syntax/Classes - Wikibooks ...</a> [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