代码之家  ›  专栏  ›  技术社区  ›  Alex Boisvert

如何以编程方式确定哪个类/模块定义要调用的方法?

  •  4
  • Alex Boisvert  · 技术社区  · 15 年前

    假设在我调用的给定范围内 some_method() . 在相同的范围内,我想调用一个函数 find_method(:some_method) 它将返回哪个类、单例类或模块定义的 some_method .

    这里有一些代码来说明我的意思:

    class Foo
      include ...
    
      def bar
        ...
        some_method() # calls a method in scope, assume it exists
    
        find_method(:some_method) # Returns where the method is defined
                                  # e.g. => SomeClassOrModule
        ...
      end
    end
    

    self self.ancestors 使用 method_defined? instance_eval ).

    我只是不知道要实现的Ruby元模型的正确顺序和所有微妙之处 find_method 因此,从方法分派解析的角度来看,它在搜索方面是详尽无遗的,而且是正确的。

    谢谢!

    1 回复  |  直到 15 年前
        1
  •  8
  •   Community Mohan Dere    9 年前

    发现这很简单。整洁!

    扩展 this answer ,以显示如何实际返回所有者类:

    foo.method(:some_method).owner