O'Reilly logo

Mastering Ruby Closures by Benjamin Tan Wei Hao

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

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

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