Procs and the Four Ways of Calling Them

Unlike the language named after a certain serpent, Ruby embraces TMTOWTDI (pronounced as Tim Toady), or There’s more than one way to do it. The calling of Procs is a wonderful example. In fact, Ruby gives you four different ways:

  1. Proc#call(args)

  2. .(args)

  3. Threequals

  4. Lambdas

Fire up irb. Let’s begin by creating a very simple Proc:

 >>​ p = proc { |x, y| x + y }
 =>​ ​#<Proc:0x007ffb12907940@(irb):1>

There are two things to notice here. First, the return value tells you that a Proc has been created. Second, Ruby provides a shorthand to create Procs. This is really a method in the Kernel class:

 >>​ p = Kernel.proc { |x, y| x + y }
 =>​ ​#<Proc:0x007ffb12907940@(irb):1>

Of course, since Proc is ...

Get Mastering Ruby Closures 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.