Blocks and Closures in Ruby
So, I’ve finally started doing actual research for this presentation beyond asking, “What do I already know?” First stop on the research train? Blocks and Closures in Ruby over at Artima. It’s an interview with Matz (the creator of Ruby for those of you not in the know) discussing how cool it is that Ruby supports blocks and closures. Read on to get an abrievated version of what goes on in the article.
“What are blocks and closures?” you ask. Only the most fundamental construct necessary for higher order procedures. (Word of warning, I’ll be using procedures and functions interchangebly.) Blocks allow you to create an anonymous function and pass it directly to another function. Closures on the other hand allow you to create a function that you then assign to a variable name. What makes this function special, however, is that it maintains a ton of information related to where it was created. For example, if it were created inside an object called king_biscuit, then its value of self is king_biscuit, regardless of if it is called from within king_biscuit or queen_pancake.
Enough about state though, we’re really interested in the passing functions around part. The real benefit of blocks and closures is that they allow us to treat functions as data. We can then pass this data to another function to create cool combinations such as “array.collect {|x, y| x + y}” which will sum up a bunch of numbers. This is in opposition to
result = 0 for item in array result += item end
The bad way (for loop) does not allow us to give a name to what happens when we use a function to collect all of the values of an array. However, the good way (array.collect) gives us a name that we can then discuss with other people. Blocks and closures, the basic building blocks (woo hoo puns!) of higher order procedures give us an extra way to discuss processes, which increases our programming power.
P.S. – If you look at the original definition of “closure”, my use of the word is not the same. However, this is the use of “closure” to which the Ruby community adheres, so deal with it.