在这个代码块中,
@@y = 1
class MyClass
@@y = 2
end
p @@y # => 2
天真地,它似乎@@y在顶级范围内,并且与' 范围内@@y的不一样。MyClass为什么会@@y受到类MyClass定义的影响?(为什么是结果2?)
在这个代码块中,
@@y = 1
class MyClass
@@y = 2
end
p @@y # => 2
天真地,它似乎@@y在顶级范围内,并且与' 范围内@@y的不一样。MyClass为什么会@@y受到类MyClass定义的影响?(为什么是结果2?)
让我们看看这个例子。这里@@xin确实与inBar分开。@@xFoo
class Foo
@@x = 1
end
class Bar
@@x = 2
end
Foo.class_variable_get(:@@x) # => 1
Bar.class_variable_get(:@@x) # => 2
但是,如果Bar是 的孩子,会发生什么Foo?
class Foo
@@x = 1
end
class Bar < Foo
@@x = 2
end
Foo.class_variable_get(:@@x) # => 2
Bar.class_variable_get(:@@x) # => 2
在这种情况下,@@x在两种情况下都是相同的,并且它是在 中声明的那个Foo。
现在,回到你的例子:
@@y = 1
class MyClass
@@y = 2
end
p @@y
第一行在根范围内声明类变量。mainRoot 是一个类型为 的特殊对象Object。所以,本质上,你是在 class 上定义一个类变量Object。由于一切都是一个Object,这就是定义的MyClass也继承@@y并能够改变它的方式。
当你这样做
@@y = 1
你在对象上定义它。由于 MyClass 是 Object 的子类,因此它可以访问它的类变量。
@@y = 1
class MyClass
@@y = 2
end
p @@y
puts MyClass.superclass #=> Object
puts Object.class_variables #=> @@y