gpt4 book ai didi

ruby - Ruby 的方法查找路径

转载 作者:数据小太阳 更新时间:2023-10-29 08:39:17 28 4
gpt4 key购买 nike

我正在阅读“Well Grounded Rubyist”一书,我对方法查找路径有疑问:

module M
def report
puts "'report' method in module M"
end
end

module N
def report
puts "'report' method in module N"
end
end

class C
include M
include N
def report
puts "'report' method in class C"
puts "About to call super..."
super
puts "Back from super..."
end
end

obj = C.new
obj.report

根据我的理解,obj.report 会输出:

'report' method in class C
About to call super...
'report' method in module N
Back from super...

但是,我很好奇是否可以通过绕过 N 的报告,从类 C 中调用 M 的报告方法。我知道如果我在模块 N 中添加“super”,它会调用 N 的报告,然后调用 M 的报告在放置“从 super ...返回”之前,但是有没有办法直接从 C 执行此操作?

最佳答案

你可以使用祖先反射:

class C
def report
my_ancestors = self.class.ancestors
puts "my ancestors are: #{my_ancestors}"
method = my_ancestors[2].instance_method(:report)
method.bind(self).call
end
end

C.new.report
=> my ancestors are: [C, N, M, Object, PP::ObjectMixin, Kernel, BasicObject]
=> 'report' method in module M

关于ruby - Ruby 的方法查找路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14573871/

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