Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert method or lambda to non-lambda proc

Tags:

ruby

lambda

proc

As shown in the ruby example below, I can't call a lambda with wrong number of arguments as Proc created from a Method because it is strict about the number of arguments:

# method with no args
def a; end

instance_eval(&method(:a))
# ArgumentError: wrong number of arguments (1 for 0)

method(:a).to_proc.call(1, 2, 3)
# ArgumentError: wrong number of arguments (3 for 0)

method(:a).to_proc.lambda?
# => true

How do I get a Proc that is not a lambda from either a Proc that is or from a Method?

like image 989
michelpm Avatar asked Apr 24 '13 16:04

michelpm


People also ask

What is the difference between a proc and a lambda?

Procs return from the current method, while lambdas return from the lambda itself. Procs don't care about the correct number of arguments, while lambdas will raise an exception.

What are procs in Ruby?

A Proc object is an encapsulation of a block of code, which can be stored in a local variable, passed to a method or another Proc, and can be called. Proc is an essential concept in Ruby and a core of its functional programming features.

How is a block different from a proc?

Procs are objects, blocks are notA proc (notice the lowercase p) is an instance of the Proc class. This lets us call methods on it and assign it to variables. Procs can also return themselves. In contrast, a block is just part of the syntax of a method call.


1 Answers

There is no way to do this.

Besides the argument passing, I wonder what you would expect from a return in the method. It can only behave in lambda way...

If you really have to do this, you will need to build your own block, e.g.

Proc.new{ a }

For a more generic way, you'll have to check the arity of the method and pass only the required parameters.

like image 64
Marc-André Lafortune Avatar answered Nov 04 '22 20:11

Marc-André Lafortune