By

Blocs, Procs, and Lambdas...oh my!

Technical Blog Post 6

Blocks

Blocks are bits of code that can be executed and can be defined with either the keywords do and end or with {}. We have worked a lot with blocks so far in Dev Bootcamp because many methods take a block. For example, in

array.each {|x| x*2}

anything in the curly brackets is a block that is passed to the method. Unlike a method, though, the block we define will only be called once and in the context of the array we are iterating over. The block appears just long enough to do something for “each”, then disappears.

It is also possible to transfer control from a calling method to a block and back again using the yield keyword. Here is an example of what that would look like. When the block_test method is called, yield outputs anything that is inside the curly brackets.

It is important to realize that blocks are one of very few things in Ruby that are not objects. Let me say that again: blocks are NOT objects. What if we wanted to save a block as an object? That’s where procs and lambdas come in.

Procs

A proc is an object that stores a block so that you can call it whenever you’d like without having to rewrite it. It is similar to a method, yet it isn’t bound to an object since it IS an object itself. You can output the result of a proc with the .call method or pass a proc to a method. Procs often look similar to methods.

Here is an example of calling a proc with .call:

Here is an example of passing a proc to a method:

Lambda

Lambdas, which are like nameless methods, are similar to procs. lambda{puts “hello”} is the same as Proc.new {puts “hello”}.Unlike procs, lambdas check the number of arguments passed to it and will throw an error if you pass it the wrong number of arguments. Also, when a lambda returns, it passes control back to the calling method, while a proc returns immediately.

Further Reading

The Codecademy lesson on blocks, procs, and lambdas is very helpful, so if you want to learn more, I would suggest going through it here.