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(where xreferences an instance of 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 回答