A companion to Enumerable#inject : Enumerable#build

Posted by collin
on Tuesday, August 19

This was a patch idea I had for Rails. Enumerable#inject is great, but there is a little extra bit of code cruft that I see popping up everywhere with regards to using #inject to create a new array or hash. Since the return value of the block passed into #inject becomes the next value of the accumulator, you often see this:

result = (1..10).inject([]) do |array, element|
  array << element if element % 2 == 0
  array
end

puts result.inspect # => [2, 4, 6, 8, 10]

I’d like to see another method added to Enumerable, something like:

module Enumerable

  def build(accumulator)
    each do |item|
      if result = yield(accumulator, item)
        accumulator = result
      end
    end
    accumulator
  end

end

The #build method would essentially reassign the accumulator only if the return value of #yield was non-false. This would shorten the above example into:

result = (1..10).build([]) do |array, element|
  array << element if element % 2 == 0
end

puts result.inspect # => [2, 4, 6, 8, 10]

So yes, one line of savings, but I feel the meaning here is much more clear than the first case using #inject.

Comments

Leave a response

  1. marcAugust 25, 2008 @ 05:05 PM

    Hi, Collin (I’m assuming this is you),

    I’m the guy from the coffeeshop today (I’m Marc) to whom you gave the threadless.com recommendation-thanks so much! I found a great t-shirt there that I’ve ordered (it’s a grotesque Little Red Riding Hood one in green), and I think this site’s going to become one of my favorite. Hopefully I’ll run into you again at Goats sometime soon, and I’ll say thanks in person :)

  2. marcAugust 25, 2008 @ 05:06 PM

    p.s. I have no idea why that struckthrough half my post.

  3. Collin VanDyckAugust 25, 2008 @ 05:45 PM

    Hey Marc

    Ah, glad you like threadless! It’s one of my favorite sites now, too, thanks to my friend Mark Jones, who was one of the other guys at the table today. He started this (somewhat expensive) habit of mine :)

    The reason it struck through your post is probably because it’s using “textile” to format the posts, which turns certain characters into other things. In some cases, it will turn a dash into a strikethrough HTML tag. For the most part it actually works pretty well, but every now and then you get an unexpected oddity :)

    I’m at the Goat every week or two, so I’ll probably be seeing you there in the future.

    -Collin