我的代码使用SimpleDelegator
require 'delegate'
class Foo < SimpleDelegator
def meth
p 'new_meth'
end
end
class Bar
def meth
p 'old_meth'
end
def bar_meth
meth
end
end
bar = Bar.new
foo = Foo.new(bar)
foo.meth #=> "new_meth"
foo.bar_meth #=> "old_meth"
为什么最后一行给出 "old_meth"
???!!!谢谢!
最佳答案
Delegator
说:
This library provides three different ways to delegate method calls to an object. The easiest to use is SimpleDelegator. Pass an object to the constructor and all methods supported by the object will be delegated. This object can be changed later.
好的,现在看一下输出,它位于符号# =>
的右边。 .
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)
行时,然后输出( #<Method: Foo#meth>
)确认无论何时您将调用 foo.meth
, 然后 meth
Foo
的方法类将被调用。但是行 foo.bar_meth
outputs( #<Method: Bar#meth>
) 只是说在方法内部 bar_meth
, 如果你打电话 meth
然后方法,Bar#meth
将被调用。
A concrete implementation of Delegator, this class provides the means to delegate all supported method calls to the object passed into the constructor and even to change the object being delegated to at a later time with #setobj.
是的,在你的情况下foo
对象已设置为 bar
对象,通过使用 #__setobj__
. foo.__getobj__
行的输出正在表明这一点。
关于ruby - 奇怪的 SimpleDelegator 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18163877/