查看类变量

类和模块具有与任何其他对象相同的内省实例变量的方法。类和模块也有类似的方法来查询类变量(@@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
  end
end

class Bar < Foo; end

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

与实例变量类似,类变量的名称必须以 @@ 开头,否则你将收到错误:

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