Picture of admin

List comprehensions versus blocks/closures

  • Posted By admin on October 08, 2005
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 = [e.office 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 = employees.select{|e| e.manager?}.map {|m| m.office}"

Let’s make the block form look nicer:

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

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.