By

Inject...And Not the Needle Kind

Technical Blog Post 4

I learned about an awesome Ruby method this week. So awesome that I have to share it. That method is Enumerable#inject. When I first started learning Ruby, I did a bunch of exercises that involved writing loops and .each iterators to add every element in an array together, then return the sum of all the elements. This required a large block of code. Here is an example of how such code looked using a while loop.

Here is an example of how such code would look using an each iterator.

And then, I discovered inject, which makes it possible to do this using just ONE LINE OF CODE! Inject is a method in the Enumerable module, which is a set of methods to traverse, search through and manipulate collections. The inject method takes a collection and reduces it to a single value, such as a sum, product, or difference of values. You can even use inject to find the longest string in an array or to convert an array into a hash.Synonyms for inject include reduce, fold, accumulate, and compress.

What’s happening in the code below is inject is storing values in a block variable called memo, then returning the total that is in memo. You can call memo anything you’d like, but it is common practice to call it memo. Note the argument passed to inject is the initial value.