Blocks, Procs and Lambdas

By on

Block

A block in Ruby is a type of syntax. To demonstrate a block, let’s use the enumerable #each.

We can use a block as an argument to the method, we need the yield keyword to do so, make sure that there is a block when the method is called (see lines 6 - 7 below).

Proc

By calling a Proc, you can use the block of code more than once in your program since it’s an object, which blocks are not. By using the call method on line 3, the block on line 7 to 9 gets executed. Line 4 just shows you what Class proc is.

Lambda

A lambda is a proc object, check out lines 5 and 15 below. It is like Proc but they have differences.

Procs and lambdas are blocks assigned to variables. Procs and lambdas are created similarly. Here are some of the differences between Procs and lamdas:

  1. Lambdas will throw errors if it doesn’t find the correct number of arguments it requires.

  2. Procs and lambdas are different in the way they return. You can watch the video here.

You can read more about blocks, procs and lambdas here.