Vlad the Impala
Vlad the Impala

Reputation: 15872

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)

Upvotes: 1

Views: 92

Answers (2)

inger
inger

Reputation: 20184

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)

Upvotes: 0

Phrogz
Phrogz

Reputation: 303146

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

Upvotes: 7

Related Questions