如何确定指定方法的起源类?

eri*_*223 7 ruby

我从这个讨论中得到了这个问题.方法调用object.m并不总是意味着"对象"类具有"m"方法,就像Array对象的find方法不是直接来自Array对象,而是来自混合的Enumerable模块.我的问题是,给定一种方法,我们如何确定方法起源的类?

Tob*_*ede 10

任何类/对象方法都是Ruby中的一个对象,并且有一些自己的方法.

所以你可以这样做:

[].method(:count).inspect
=> "#<Method: Array#count>"

[].method(:detect).inspect
=> "#<Method: Array(Enumerable)#detect>"
Run Code Online (Sandbox Code Playgroud)

RegEx的快点,你已经完成了.


ben*_*n_h 7

tobyhede的答案很棒,但我只是做了一些挖掘irb而且没有必要切断输出#inspect.该Method

>> Object.new.method(:inspect)
=> #<Method: Object(Kernel)#inspect>
Run Code Online (Sandbox Code Playgroud)

有一些有用的方法:

>> Object.new.method(:inspect).methods - Object.methods
=> ["owner", "call", "to_proc", "unbind", "arity", "receiver", "[]"]
Run Code Online (Sandbox Code Playgroud)

特别是该#owner方法,它将所有者作为适当的对象返回:

>> [].method(:count).owner
=> Array
>> [].method(:detect).owner
=> Enumerable
Run Code Online (Sandbox Code Playgroud)