Delegator说:
该库提供了三种不同的方法来将方法调用委托给对象。最容易使用的是SimpleDelegator。将对象传递给构造函数,该对象支持的所有方法都将被委托。以后可以更改此对象。
好的,现在看一下符号右侧的输出# =>。
require 'delegate'
class Foo < SimpleDelegator
def meth
p 'new_meth'
end
end
class Bar
def meth
p 'old_meth'
end
def bar_meth
self.method(:meth)
end
end
bar = Bar.new # => #<Bar:0x8b31728>
foo = Foo.new(bar)
foo.__getobj__ # => #<Bar:0x8b31728>
foo.bar_meth # => #<Method: Bar#meth>
foo.method(:meth) # => #<Method: Foo#meth>
因此,当我使用该行时foo.method(:meth), output( #<Method: Foo#meth>) 确认无论何时调用foo.meth,都会调用该类meth的方法。Foo但是该行foo.bar_methoutputs( #<Method: Bar#meth>) 只是说在方法内部bar_meth,如果您调用meth方法,Bar#meth则将被调用。
SimpleDelegator说:
Delegator 的具体实现,此类提供了将所有支持的方法调用委托给传递给构造函数的对象的方法,甚至可以在以后使用 # setobj更改被委托的对象。
是的,在您的情况下,foo对象已设置为bar对象,使用#__setobj__. 该行的输出foo.__getobj__显示了这一点。