Quick tip: ruby’s inject method

If you’ve been using the online version of the Pickaxe book as your ruby reference, you won’t know about this very useful little method in the Enumerable module. It allows you to do something cumulative with each item in your Enumerable object.

For example, to sum prices in an array of items ordered:

order = [item0, item1, item2]
total_price = order.inject(0) {|sum, item| sum + item.price}

instead of:

order = [item0, item1, item2]
total_price = 0
order.each {|item| total_price += item.price}

Notes:

  • The method parameter is the starting value for whatever the cumulative value is - in this case, sum.
  • The first block parameter is the cumulative value, the second is the current object from the Enumerable.
  • The value returned by the statement in the block is set as the starting value for the next object from the Enumerable.

For more details, see this article on ruby arrays on thinkvitamin.com.

Leave a Reply