Blocks, Procs, and Lambdas

Also known as "closures"

May 17, 2015

Ruby blocks, procs, and lambdas are basically closures. In Ruby, we've already seen one of them many times: blocks! Whenever we use an enumerable, such as each or map, we are sending a block of code to the Array or object we are calling the enumberable method on. For example, our block here is the code between the brackets:

What's up with Procs?

Procs, aka Procedures, come in handy when we want to use a block over and over again. We don't want to have to repeat ourselves, so we can actually save a reusable chunk of code as an object itself, which is a Proc! Technically, a block is a Proc (and a Proc is a block?! yes), but it's a "reduced," temporary version that makes it easy for us to use methods like each and select. Procs are the real deal - think of them as more permanent, portable chunks of code. You can save Procs to a variable, like so:


Lastly, we have lambdas, which we'll see a little less typically. Lambdas are basically functions. They are comparable to what's known as the anonymous function in JavaScript. They check the number of arguments passed and their last expression is a return value. Returns will return only from the lambda itself, not from the method it's enclosed in (if it's enclosed in a method at all). Let's say we have an area in our code where we want to return 5 if our made up game needed our flavor to be "cherry":

This lambda will return 5 since our argument is indeed "cherry." I'll stop here. We won't be using these concepts for a while, but I learned a little about each and hope you did, too!