【问题标题】:In Ruby, is there a way to find the class that responds to a method call?在 Ruby 中,有没有办法找到响应方法调用的类?
【发布时间】:2014-05-01 19:35:46
【问题描述】:

所以,在 Ruby 中,如果我的类层次结构看起来像(非常象征性地)

ABCObject

并且在类C 中定义了一个方法"foo",是否有一些内省 让我可以确定C 是定义响应@987654328 的方法的类@?

【问题讨论】:

    标签: ruby introspection


    【解决方案1】:

    是的...做A.new.method(:foo).owner。它会给你上课C。阅读#owner

    【讨论】:

      【解决方案2】:

      Method#owner 是为此专门构建的,但也可以使用:

      A.ancestors.find { |c| c.instance_methods(false).include? :foo }
      

      【讨论】:

        猜你喜欢
        • 2017-12-04
        • 2010-09-06
        • 1970-01-01
        • 2022-11-07
        • 1970-01-01
        • 1970-01-01
        • 2011-05-20
        • 2019-11-30
        • 1970-01-01
        相关资源
        最近更新 更多