Skip to content

Instantly share code, notes, and snippets.

@jesjos
Created February 20, 2015 09:38
Show Gist options
  • Save jesjos/4d029da5294f79b789af to your computer and use it in GitHub Desktop.
Save jesjos/4d029da5294f79b789af to your computer and use it in GitHub Desktop.
Class variables
class Foo
@@klass = "class level variable"
@klass_instance = "class instance level variable"
end
class Bar < Foo
end
puts Foo.instance_variables.inspect # => [:@klass_instance]
puts Foo.class_variables.inspect # => [:@@klass]
puts Foo.instance_variable_get(:@klass_instance)
# => "klass instance level variable"
puts Foo.class_variable_get(:@@klass)
# => "class level variable"
# The class variable is inherited, but the class instance variable is not
puts Bar.instance_variables.inspect # => []
puts Bar.class_variables.inspect # => [:@@klass]
# The @@klass variable is shared between all classes in the downward inheritance chain
# So for example:
Foo.class_variable_set(:@@klass, "foo")
puts Bar.class_variable_get(:@@klass) # => "foo"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment