Ruby Tuesday #21 : Closures
It seems impossible to avoid closures when reading about Ruby. What is slightly unclear is what exactly one of these closure things is and what they should be used for. According to Wikipedia, a closure is:
"a function that is evaluated in an environment containing one or more bound variables. When called, the function can access these variables"
Not much clearer? Here’s Martin Fowler’s contribution:
"Essentially a closure is a block of code that can be passed as an argument to a function call."
He goes on to explain that a key feature of closures is that:
"they are a block of code plus the bindings to the environment they came from"
Which leads us back to the Wikipedia definition. He also points out that in a language that doesn’t support closures, he misses them. I get the feeling that this is a language construct which is best understood by usage rather than explanation. And there’s some stylistic preferences. Consider this example from a useful primer on closures:
@person = Person.find(id)
respond_to do |wants|
wants.html { render :action => @show }
wants.xml { render
ml => @person.to_xml }
end
The author describes this code as "beautiful to look at, and with a quick glance, you can tell exactly what it does" – I’m not sure I agree on either point. I’ve seen a fair amount of Ruby that has impressed me with its expressiveness – this excerpt doesn’t make that list. In my search for more insight into closures, I found this is a good starting point – an executable piece of exploration (found via RubyInside.)