Cover by David Flanagan, Yukihiro Matsumoto

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

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 forms

  • How to invoke Proc objects

  • How to determine how many arguments a Proc expects

  • How to determine if two Proc objects are the same

  • How 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required