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
Procobjects in both proc and lambda formsHow to invoke
ProcobjectsHow to determine how many arguments a
ProcexpectsHow to determine if two
Procobjects 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access