简体   繁体   English

是否有将proc转换为Ruby中的方法的标准方法

[英]Is there a standard way to convert a Proc to a Method in Ruby

Is there some way to do this in Ruby?: 有没有办法在Ruby中做到这一点?

add = lambda { |x, y| x + y }
add_m = add.to_method
add_m(3, 4)
add = lambda { |x, y| x + y }
define_singleton_method(:add_m,&add)
p add_m(3,4)
#=> 7

Note, however, that you can call a lambda like a method, but with square brackets: 但是请注意,您可以像方法一样调用lambda,但要使用方括号:

add = lambda { |x, y| x + y }
p add[3,4]
#=> 7

Don't think you can get exactly that, partly because there is no easy way to get the name of the variable/symbol you are binding to. 不要以为您能确切地做到这一点,部分原因是没有简单的方法来获取要绑定的变量/符号的名称。

The nearest match IMHO: 最接近的匹配恕我直言:

class Proc
   def to_method(m)
     p=self
     Object.class_eval {define_method(m, &p)}     
   end;
 end

 add = lambda { |x, y| x + y }
 add.to_method(:add_m)
 add_m(3, 4)

If it's not the Object you want to add the method to, you should pass in the class too. 如果不是要向其添加方法的对象,则也应该传入该类。

If syntax doesn't matter too much, you can go with the Phrogz' suggestion: add[3,4], 如果语法没什么大不了的话,可以采用Phrogz的建议:add [3,4],

or just 要不就

add.call(3,4)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM