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
?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With