想一想,它的一个好方法是绑定是封装上下文的对象。您可以使用关键字binding
揭示绑定对象:
a = 10 # a is defined in the 'main' context
def get_binding # so is the 'get_binding' method
b = 20
binding
end
n = get_binding #=> #<Binding:0x00...>
现在,因为get_binding
是main
范围内确定,返回的绑定对象包括方法的当地情况,以及主要范围内任何东西。变量b
在main
中不可用,而a
在get_binding
中可用。
您可以通过使用eval
绑定对象交互证明这一点:
a #=> 10
eval('a', n) #=> undefined local variable or method 'a' for main:Object
b #=> undefined local variable or method `b' for main:Object
eval('b', n) #=> 20 # but it is defined within the context the n binding was created.
只是为了澄清 - 这个例子只是揭示了幕后发生了什么。如果有的话,你将很少需要直接处理绑定对象。
Ruby模块,类和方法揭示了它们绑定到比它们低的层次结构的对象,但不是相反,除非它们通过公共实例方法等明确公开。这是一种过分简单化,但如果你不熟悉编程,就没有必要深入了解这一点。
感谢您的解释!根据你所说的,似乎变量绑定是特定于范围的权利?我的意思是,当你谈论变量绑定时,你必须提供范围作为上下文才能使其有意义。 – wmock 2013-02-16 04:53:00
@WillsonMock这是正确的。 – sawa 2013-02-16 04:58:01