为什么不能在 Ruby 中的 singleton-class 定义中访问 class 实例变量?
Why can't a class instance variable be accessed in a singleton-class definition in Ruby?
class MyClass
@my_class_instance_variable = "here"
p @my_class_instance_variable # => "here"
class << self
p @my_class_instance_variable # => nil
end
end
class MyClass
p @my_class_instance_variable # => "here"
end
为什么第二个 p
打印 nil
,而第三个 p
打印 "here"
?我对单例 class 定义 (class << self
) 的理解是它与 class 定义 (class MyClass
).
具有相同的作用域
(这个question的标题相似,但侧重点不同。)
My understanding of a singleton class definition (class << self) is
that it has the same scope as a class definition
没有。适用范围不同。您在 MyClass
的范围内定义了 @my_class_instance_variable
,但试图在 MyClass
的单例 class.
范围内访问它
检查起来很容易:
class Foo
puts self #=> Foo
class << self
puts self #=> #<Class:Foo>
end
end
输出为:
Foo
#<Class:Foo>
class MyClass
@my_class_instance_variable = "here"
p @my_class_instance_variable # => "here"
class << self
p @my_class_instance_variable # => nil
end
end
class MyClass
p @my_class_instance_variable # => "here"
end
为什么第二个 p
打印 nil
,而第三个 p
打印 "here"
?我对单例 class 定义 (class << self
) 的理解是它与 class 定义 (class MyClass
).
(这个question的标题相似,但侧重点不同。)
My understanding of a singleton class definition (class << self) is that it has the same scope as a class definition
没有。适用范围不同。您在 MyClass
的范围内定义了 @my_class_instance_variable
,但试图在 MyClass
的单例 class.
检查起来很容易:
class Foo
puts self #=> Foo
class << self
puts self #=> #<Class:Foo>
end
end
输出为:
Foo
#<Class:Foo>