enum#inject
One of the very handy features of Ruby is the use of blocks. Blocks allow us to interate over a collection of some kind (think arrays) and perform some action on each item in the collection. This gives rise to methods like enum#inject. This handy little method of the enumerable module allows us to do summation operations on the contents of a collection. It looks like this:
(1..5).inject {|sum, n| sum + n}
=> 15
If you are new to Ruby, the (1..5) is a range, basically equal to [1,2,3,4,5] an array of 1 through 5. The inject method uses an accumulator object, sum in this case. It loops over the array passing in each object and adding the object to sum and finally returning sum which is 15 in this case.
One very handy use for this method is summing totals for tables in RoR. If you have a collection of objects that have a price variable for instance, you could do something like this to get a total instead of trying to keep a running total as you output the rows containing the objects' data.
@items.inject(0.0) {|memo, u| u.price + memo}
Here each item object in the @items array has a price. We give it a starting value of 0.0 to create a float object for our accumulator and let inject add all of the prices together to get our total. It is a slick way to accumulate totals on a array. Hopefully you can find a use for it too.
Twitter