Created
February 20, 2015 09:38
-
-
Save jesjos/4d029da5294f79b789af to your computer and use it in GitHub Desktop.
Class variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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