获取ruby函数对象本身 [英] Getting ruby function object itself

查看:112
本文介绍了获取ruby函数对象本身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中,一切都应该是一个对象。但是我有一个很大的问题需要定义常用的函数对象,比如

  def f 
foo
end

与Python不同,f是函数结果,而不是函数本身。因此, f() f ObjectSpace.f 都是foo f.methods 只返回字符串方法列表。



如何访问函数对象本身?

解决方案

您只需使用方法方法。这将返回与该方法匹配的方法实例。一些例子:

 >> def f 
>> foo
>>结束
=>无
>> f
=> foo
>>方法(:f)
=> #<方法:Object#f>
>>方法(:f)。方法
=> [:==,:eql ?,:hash,:clone,:call,:[],...]
>> class SomeClass
>> def f
>> bar
>>结束
>>结束
=>无
>> obj = SomeClass.new
=> #< SomeClass的:0x00000001ef3b30>
>> obj.method(:f)
=> #<方法:SomeClass#f>
>> obj.method(:f).methods
=> [:==,:eql ?,:hash,:clone,:call,:[],...]

希望这有助于。


In Ruby, everything is supposed to be an object. But I have a big problem to get to the function object defined the usual way, like

def f
    "foo"
end

Unlike in Python, f is the function result, not the function itself. Therefore, f(), f, ObjectSpace.f are all "foo". Also f.methods returns just string method list.

How do I access the function object itself?

解决方案

You simply use the method method. This will return the Method instance that matches with that method. Some examples:

>> 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, :[], ...]

Hope this helps.

这篇关于获取ruby函数对象本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆