Friday, March 02, 2007

Ruby code blocks

I first started looking at Ruby in late 2005/early 2006 as part of a project at work. While the Ruby aspects of the project were eventually eaten by the vagaries of the IBM funding process, my fascination with the language continues. One thing about Ruby that really clicked with me was the use of code blocks.

Looking over the Ruby code I've written, it appears that I like them a lot, but it didn't occur to me until a few days ago to wonder why. I put a (very) little bit of thought into it and here are the reasons I came up with:

1. They allow me to represent a chunk of code as first-class object. This is horribly trite and pretty much straight out of the Ruby books, but it happens to be true. I never used to think this would be all that useful; then I used it. Man, was I wrong.

2. I can express my intentions so much more precisely and succinctly. The important bits of my code's logic all seem to wind up in the code blocks, and the boilerplate all seems to fade into the method calls and parameters. I have no idea if this is a universal in the Ruby world or just my style of writing Ruby, but I like it.

3. They are way more versatile than I ever guessed. Besides the obvious uses like iterator bodies (with each), accumulators (with inject), discriminators (with select/reject), pluggable algorithms (e.g. comparators) and elegant try/finally blocks (e.g., I have used them as (re)initializers, validators, formatters, slicers, dicers and julienne fry-makers.

My biggest gripe is that I can only pass one code block to a method. I know I could do or Kernel.lambda, but they just don't have the same elegance.