class Meh
@@test = "meh"
end
p Meh.class_variables
class Roar
@@common_var = "lion"
def common_var
@@common_var
end
end
class Mew
@@common_var = "kitty"
def common_var
@@common_var
end
end
cat = Mew.new
bigcat = Roar.new
p cat.common_var
p bigcat.common_var
##somewhere else in the program in the Object namespace.
@@@@common_var = "gorilla"
p cat.common_var
p bigcat.common_var
class Roar # instantiates a new Class object
def speak
"mew"
end
end
Roar = Class.new
Roar = Class.new
def Roar.speak
"mew"
end
Roar = Class.new
Roar.send(:define_method,:speak) do
"mew"
end
class Foo
@@@@a = "class variable"
@a = "class instance variable"
def initialize
@a = "object instance variable"
end
end
class<<Foo
@a = "class metaclass variable"
end
f = Foo.new
class<<f
@a = "object metaclass variable"
end
puts "#{Foo.class_variables} = #{Foo.class_eval '@@a'}"
puts "#{Foo.instance_variables} = #{Foo.instance_variable_get :@a}"
puts "#{(class<<Foo;self;end).instance_variables} = #{(class<<Foo;self;end).instance_variable_get :@a}"
puts "#{f.instance_variables} = #{f.instance_variable_get :@a}"
puts "#{(class<<f;self;end).instance_variables} = #{(class<<f;self;end).instance_variable_get :@a}"
$ ruby vars.rb
@@@@a = class variable
@a = class instance variable
@a = class metaclass variable
@a = object instance variable
@a = object metaclass variable
Diagram of objects
f (object instance)
| @a
|
`f (object metaclass)—-Foo (class instance) —- Object (class instance)
@a | @a
|
`Foo (class metaclass)
@a
class Val
@var = "easily confused" # Initialize our variable?
def initialize
@var = "With this."
end
end
I thought maybe a class variable was simply an instance variable on the class object itself.
[]
If anyone–*cough tyche*– could shed some light on this I would appreciate it.
I would have expected class_variables to be a method for Object.