Ruby Language View Class Variables


Classes and modules have the same methods for introspecting instance variables as any other object. Class and modules also have similar methods for querying the class variables (@@these_things):

p Module.methods.grep(/class_variable/)
#=> [:class_variables, :class_variable_get, :remove_class_variable,
#=>  :class_variable_defined?, :class_variable_set]

class Foo
  @@instances = 0
  def initialize
    @@instances += 1

class Bar < Foo; end

5.times{ }
3.times{ }
p Foo.class_variables                   #=> [:@@instances]
p Bar.class_variables                   #=> [:@@instances]
p Foo.class_variable_get(:@@instances)  #=> 8
p Bar.class_variable_get(:@@instances)  #=> 8

Similar to instance variables, the name of class variables must begin with @@, or you will get an error:

p Bar.class_variable_defined?( :instances )
#=> NameError: `instances' is not allowed as a class variable name