List comprehensions versus blocks/closures

I have been catching up on reading lately and have particularly enjoyed Martin Fowler's Bliki. Reading CollectionClosureMethod helped me crystallize me why I much prefer blocks/closures over list comprehensions. In fact, I'd take things a step farther. The article argues that while closures are more general, list comprehensions offer a convenient syntax in some cases:

List comprehensions make it easy to combine the two.

  managersOffices = [ for e in employees if e.isManager]

You can also do this be chaining block methods together (which looks a little more clunky to my eye).

  managersOffices ={|e| e.manager?}.map {|m|}"

Let's make the block form look nicer:

  # usage: employees.mapsome {|e| if e.manager}
  module Enumerable
    def mapsome(&blk) {|e|}.compact

Ruby already has something quite similar to mapsome: Nano Methods'compact_collect. I love the implication that Nano makes about Ruby: the language is so concise & powerful that the useful unit of component reuse is the single method.

Get In Touch