In Ruby, in the context of a class method, what are instance and class variables?
People seem to be ignoring that the method is a class method.
@blih will be instance variable of the instance of class Class for the constant Bleh. Hence:
irb(main):001:0> class Bleh
irb(main):002:1> def self.bleh
irb(main):003:2> @blih = "Hello"
irb(main):004:2> @@blah = "World"
irb(main):005:2> end
irb(main):006:1> end
=> nil
irb(main):007:0> Bleh.instance_variables
=> []
irb(main):008:0> Bleh.bleh
=> "World"
irb(main):009:0> Bleh.instance_variables
=> ["@blih"]
irb(main):010:0> Bleh.instance_variable_get :@blih
=> "Hello"
@@blah will be available as a class variable of Bleh:
irb(main):017:0> Bleh.class_variables
=> ["@@blah"]
irb(main):018:0> Bleh.send :class_variable_get, :@@blah
=> "World"
There is a method to this madness...
class Example
@foo # class instance variable
@@bar # class variable
def fun1
@baz # instance variable
end
end
Instance variables
Instance variables (@foo
and @baz
in the example) always begin with @
, and they always belong to whatever object self refers to: either an object of the class, or the Class object representing a class. An instance variable reference in a class definition or class method is completely different from an instance variable reference in an instance method.
Inheritance
Because instance variables are not defined by a class, they are unrelated to the inheritance mechanism —they are simply created when a value is assigned to them. Class instance variables, being simply instance variables of the Class object that represents a class, are thus not inherited.
Class variables
Class variables are visible to, and shared by, the class methods and the instance methods of a class, and also by the class definition itself. Class variables can be used in instance methods, class methods, and in the class definition itself, outside of any method. Class variables are always evaluated in reference to the class object created by the enclosing class definition statement.
Class instance variable vs instance variable
A disadvantage of class instance variables is that they cannot be used within instance methods as class variables can. Another disadvantage is the potential for confusing them with ordinary instance variables. An advantage of class instance variables over class variables has to do with the confusing behavior of class variables when subclassing an existing class: if a class uses class variables, then any subclass can alter the behavior of the class and all its descendants by changing the value of the shared class variable. This is a strong argument for the use of class instance variables instead of class variables.
Much of this is from the excellent "The Ruby Programming Language"