Wednesday, February 23, 2011

Inject

I just learned something awesome. I'm always doing something like this in Ruby,
  [4, 5, 6, 7].inject(0) {|t,v| t + v}

I could clean this up and do something much simpler using inject, like so,
  [4, 5, 6, 7].inject(:+)

What's more, you can run this too
  [4, 5, 6, 7].inject(:-)
  [4, 5, 6, 7].inject(:*)
  [4, 5, 6, 7].inject(:/)

And check this out, say I want the average of the numbers in this array. I just run this:
  [4, 5, 6, 7].instance_eval { inject(:+) / self.size.to_f }

Simply brilliant.

No comments:

Post a Comment