"old_meth" 为什么最后一行给-6ren">
gpt4 book ai didi

ruby - 奇怪的 SimpleDelegator 行为

转载 作者:数据小太阳 更新时间:2023-10-29 07:32:16 25 4
gpt4 key购买 nike

我的代码使用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将被调用。

SimpleDelegator 说:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com