Ruby的方法查找路径

时间:2013-01-29 00:47:44

标签: ruby

我正在阅读“Well Ground Ground 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中添加“超级”,它将调用N的报告,然后是M的报告在放入“从超级......回来”之前,有没有办法直接从C?

这样做

2 个答案:

答案 0 :(得分:3)

您可以使用祖先反射:

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

答案 1 :(得分:1)

这样可行,但我觉得必须有一个更好的方法来做到这一点而不将其改为自我:

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

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

这个的输出是:

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