檢視類變數
類和模組具有與任何其他物件相同的內省例項變數的方法。類和模組也有類似的方法來查詢類變數(@@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