Procs and Lambdas
Blocks are syntactic structures in
Ruby; they are not objects, and cannot be manipulated as objects. It is
possible, however, to create an object that represents a block.
Depending on how the object is created, it is called a
proc or a lambda. Procs have
block-like behavior and lambdas have method-like behavior. Both,
however, are instances of class Proc
.
The subsections that follow explain:
How to create
Proc
objects in both proc and lambda formsHow to invoke
Proc
objectsHow to determine how many arguments a
Proc
expectsHow to determine if two
Proc
objects are the sameHow procs and lambdas differ from each other
Creating Procs
We’ve already seen one way to create a Proc
object: by associating a block with a
method that is defined with an ampersand-prefixed block argument.
There is nothing preventing such a method from returning the Proc
object for use outside the
method:
# This method creates a proc from a block def makeproc(&p) # Convert associated block to a Proc and store in p p # Return the Proc object end
With a makeproc
method
like this defined, we can create a Proc
object for ourselves:
adder = makeproc {|x,y| x+y }
The variable adder
now refers
to a Proc
object. Proc
objects created in this way are procs,
not lambdas. All Proc
objects have
a call
method that, when invoked,
runs the code contained by the block from which the proc was created.
For example:
sum = adder.call(2,2) # => 4
In addition to being invoked, Proc
objects can be passed to methods, stored in ...
Get The Ruby Programming Language now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.