我注意到以下代码在语法上是正确的:
class Foo
bar = 3
end
Run Code Online (Sandbox Code Playgroud)
现在,我知道实例变量是由@和类变量访问的,@@但我无法弄清楚bar在这种情况下存储的位置或如何访问它.
我怎样才能找到bar范围?
它可以从同一个类主体访问。
class Foo
bar = 3
bar # => 3
end
Run Code Online (Sandbox Code Playgroud)
它是词法作用域的,因此可以从块内访问它:
class Foo
bar = 3
pr = ->{p bar}
pr.call # => 3
end
Run Code Online (Sandbox Code Playgroud)
但一旦类体关闭,即使在同一个类中也无法访问它:
class Foo
bar = 3
end
class Foo
bar # => error
end
Run Code Online (Sandbox Code Playgroud)
也不能从方法定义中访问它:
class Foo
bar = 3
def baz; bar end
new.baz # => error
end
Run Code Online (Sandbox Code Playgroud)
Ruby中类的主体只是可执行的Ruby代码.这些确实是局部变量(不需要引用),并遵循"常规"规则作为局部变量.您可以在课程正文中访问它们.如果你真的想要bar定义范围,你可以使用Kernel.binding:
class Foo
bar = 42
@@scope = binding
def self.scope
@@scope
end
end
Foo.scope.local_variables # => [:bar]
Foo.scope.local_variable_get(:bar) # => 42
Run Code Online (Sandbox Code Playgroud)
需要注意的是 - 使用def更改范围,因此,在使用的方法中,它们将不可见def.