Explaining the inject method

The inject method takes a collection and reduces it to a single value, such as a sum of values. Here are the basic workings when iterating through an array and adding the elements together:

What’s happening

[1, 2, 3, 4, 5]

.inject  takes the first element and does something to the second element; in this case adds it. [1, 2] equals to [3] (our new first element). Now our array is [3, 3, 4, 5] and again adds the first element to the next one [3, 3] equals to [6]. Our array is now [6, 4, 5]. Repeating the process we get [6, 4] totaling [10] then [10, 5] gives us our final result [15].

A shorter version

This does the same thing with less code. You can also just use array.inject(:+) . The reasons for the ‘0’ is incase there is an empty index in the array, the value of that index would be ‘0’ which would allow it to be added to the next element.

The (:+) is calling the addition symbol. Because this is a common thing to do in Ruby, the symbol has the method built in when passed to the inject method (element1 + element2).

(Visited 31 times, 1 visits today)

Leave A Comment

Your email address will not be published. Required fields are marked *