11

これが私が知らない任意のライブラリコードであると仮定します:

class Foo
  def hi
  end
end

class Bar < Foo
  def hi
  end
end

そして、パラメーターとして渡さBarれたコードがあるとします。

def check(x)
  do_something_with(x.method(:hi))
end

x.hi上記の例では、 (xのインスタンスを参照するBar)がとは異なることを知ることができますFoo#hiか?


ガレスの答えに基づいて、これは私がこれまでに得たものです:

def is_overridden?(method)
  name = method.name.to_sym
  return false if !method.owner.superclass.method_defined?(name)
  method.owner != method.owner.superclass.instance_method(name).owner
end

恐ろしいです?素敵?

4

2 に答える 2

13

あなたはこれを行うことができます:

if x.method(:hi).owner == Foo

私は Ruby のエキスパートには程遠いです。誰かがこれよりも良い方法を持っていても、私は驚かないでしょう。

于 2012-07-13T00:12:12.593 に答える
1

興味深い質問です。私は同じ質問について疑問に思いました。Bar クラスを再度開いて、メソッドが定義されている Bar のルックアップ パスの祖先を確認できます。

class Bar < Foo
  ancestors.each do |ancestor|
    puts ancestor if ancestor.instance_methods.include?(:hi)
  end
end
于 2012-07-13T00:26:18.453 に答える