完全理解Ruby类变量

spl*_*ber 3 ruby

在这个代码块中,

@@y = 1
class MyClass
 @@y = 2
end
p @@y # => 2
Run Code Online (Sandbox Code Playgroud)

天真,似乎@@y是在顶级的范围,这是不一样@@y的一个中MyClass的范围.为什么@@y受到类MyClass定义的影响?(为什么结果2?)

Ser*_*sev 7

我们来看看这个例子.这里@@xBar是确实分开@@xFoo.

class Foo
  @@x = 1
end

class Bar
  @@x = 2
end

Foo.class_variable_get(:@@x) # => 1
Bar.class_variable_get(:@@x) # => 2
Run Code Online (Sandbox Code Playgroud)

但如果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
Run Code Online (Sandbox Code Playgroud)

在这种情况下,@@x两种情况都是相同的,并且是声明的那种情况Foo.

现在,回到你的例子:

@@y = 1
class MyClass
  @@y = 2
end
p @@y
Run Code Online (Sandbox Code Playgroud)

第一行在根范围中声明了类变量.根是一个特殊的对象main是类型Object.所以,基本上,你是在类上定义一个类变量Object.由于一切都是一个Object,这MyClass也是继承的定义,@@y并且能够改变它.