简体   繁体   中英

Is there a standard way to convert a Proc to a Method in Ruby

Is there some way to do this in 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:

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],

or just

add.call(3,4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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