CommonThread

Displaying articles with tag

Sexy Inject

Posted by ben, Wed Nov 21 01:00:00 UTC 2007

I saw @pragdave twitter on a sexier looking inject statement so I figured I would monkey patch the array class to get me some sexy inject action.

class Array
  alias old_inject inject
  def inject(v=nil, &block)
    if v.is_a?(Symbol)
      old_inject {|s,n| s.send(v,n)}
    else
      old_inject(v || 0, &block)
    end
  end
end

now what used to look like this …

[1,3,5,7].inject {|sum,val| sum + val}

... now looks like this …

[1,3,5,7].inject(:+)

... and both give me 16

0 comments | Filed Under: | Tags:

Recent Articles

Categories