My Life As A Blog

Ruby Tuesday #21 : Closures

leave a comment »

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 :xml => @person.to_xml }

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.)


Written by remark

October 7, 2008 at 7:30 pm

Posted in Development, Ruby

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: