myk*_*hal 6 ruby function object
在Ruby中,一切都应该是一个对象.但是我有一个很大的问题,就是通常的方式来定义函数对象
def f
"foo"
end
Run Code Online (Sandbox Code Playgroud)
与Python不同,f是函数结果,而不是函数本身.因此,f(),f,ObjectSpace.f都是"foo".还f.methods返回字符串方法列表.
如何访问函数对象本身?
sar*_*dne 10
你只需使用该method方法.这将返回Method与该方法匹配的实例.一些例子:
>> def f
>> "foo"
>> end
=> nil
>> f
=> "foo"
>> method(:f)
=> #<Method: Object#f>
>> method(:f).methods
=> [:==, :eql?, :hash, :clone, :call, :[], ...]
>> class SomeClass
>> def f
>> "bar"
>> end
>> end
=> nil
>> obj = SomeClass.new
=> #<SomeClass:0x00000001ef3b30>
>> obj.method(:f)
=> #<Method: SomeClass#f>
>> obj.method(:f).methods
=> [:==, :eql?, :hash, :clone, :call, :[], ...]
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.