Ruby Language Introspection View Class Variables

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


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

Got any Ruby Language Question?