Need a simple explanation of the inject method

Viewed 69338
[1, 2, 3, 4].inject(0) { |result, element| result + element } # => 10

I'm looking at this code but my brain is not registering how the number 10 can become the result. Would someone mind explaining what's happening here?

18 Answers

You can think of the first block argument as an accumulator: the result of each run of the block is stored in the accumulator and then passed to the next execution of the block. In the case of the code shown above, you are defaulting the accumulator, result, to 0. Each run of the block adds the given number to the current total and then stores the result back into the accumulator. The next block call has this new value, adds to it, stores it again, and repeats.

At the end of the process, inject returns the accumulator, which in this case is the sum of all the values in the array, or 10.

Here's another simple example to create a hash from an array of objects, keyed by their string representation:

[1,"a",Object.new,:hi].inject({}) do |hash, item|
  hash[item.to_s] = item
  hash
end

In this case, we are defaulting our accumulator to an empty hash, then populating it each time the block executes. Notice we must return the hash as the last line of the block, because the result of the block will be stored back in the accumulator.

inject takes a value to start with (the 0 in your example), and a block, and it runs that block once for each element of the list.

  1. On the first iteration, it passes in the value you provided as the starting value, and the first element of the list, and it saves the value that your block returned (in this case result + element).
  2. It then runs the block again, passing in the result from the first iteration as the first argument, and the second element from the list as the second argument, again saving the result.
  3. It continues this way until it has consumed all elements of the list.

The easiest way to explain this may be to show how each step works, for your example; this is an imaginary set of steps showing how this result could be evaluated:

[1, 2, 3, 4].inject(0) { |result, element| result + element }
[2, 3, 4].inject(0 + 1) { |result, element| result + element }
[3, 4].inject((0 + 1) + 2) { |result, element| result + element }
[4].inject(((0 + 1) + 2) + 3) { |result, element| result + element }
[].inject((((0 + 1) + 2) + 3) + 4) { |result, element| result + element }
(((0 + 1) + 2) + 3) + 4
10

The code iterates over the four elements within the array and adds the previous result to the current element:

  • 1 + 2 = 3
  • 3 + 3 = 6
  • 6 + 4 = 10

What they said, but note also that you do not always need to provide a "starting value":

[1, 2, 3, 4].inject(0) { |result, element| result + element } # => 10

is the same as

[1, 2, 3, 4].inject { |result, element| result + element } # => 10

Try it, I'll wait.

When no argument is passed to inject, the first two elements are passed into the first iteration. In the example above, result is 1 and element is 2 the first time around, so one less call is made to the block.

Inject applies the block

result + element

to each item in the array. For the next item ("element"), the value returned from the block is "result". The way you've called it (with a parameter), "result" starts with the value of that parameter. So the effect is adding the elements up.

This is a simple and fairly easy to understand explanation:

Forget about the "initial value" as it is somewhat confusing at the beginning.

> [1,2,3,4].inject{|a,b| a+b}
=> 10

You can understand the above as: I am injecting an "adding machine" in between 1,2,3,4. Meaning, it is 1 ♫ 2 ♫ 3 ♫ 4 and ♫ is an adding machine, so it is the same as 1 + 2 + 3 + 4, and it is 10.

You can actually inject a + in between them:

> [1,2,3,4].inject(:+)
=> 10

and it is like, inject a + in between 1,2,3,4, making it 1 + 2 + 3 + 4 and it is 10. The :+ is Ruby's way of specifying + in the form of a symbol.

This is quite easy to understand and intuitive. And if you want to analyze how it works step by step, it is like: taking 1 and 2, and now add them, and when you have a result, store it first (which is 3), and now, next is the stored value 3 and the array element 3 going through the a + b process, which is 6, and now store this value, and now 6 and 4 go through the a + b process, and is 10. You are essentially doing

((1 + 2) + 3) + 4

and is 10. The "initial value" 0 is just a "base" to begin with. In many cases, you don't need it. Imagine if you need 1 * 2 * 3 * 4 and it is

[1,2,3,4].inject(:*)
=> 24

and it is done. You don't need an "initial value" of 1 to multiply the whole thing with 1. This time, it is doing

(((1 * 2) * 3) * 4)

and you get the same result as

1 * 2 * 3 * 4

This code doesn't allow the possibility of not passing a starting value, but may help explain what's going on.

def incomplete_inject(enumerable, result)
  enumerable.each do |item|
    result = yield(result, item)
  end
  result
end

incomplete_inject([1,2,3,4], 0) {|result, item| result + item} # => 10

One day, I was also banging my head against the default values in Ruby inject/reduce methods, so I've tried to visualize my issue:

default values vizualized

A common scenario that arises when using a collection of any sort, is to get perform a single type of operation with all the elements and collect the result.

For example, a sum(array) function might wish to add all the elements passed as the array and return the result.

A generalized abstraction of same functionality is provided in Ruby in the name of reduce (inject is an alias). That is, these methods iterate over a collection and accumulate the value of an operation on elements in a base value using an operator and return that base value in the end.

Let's take an example for better understanding.

>>> (5..10).inject(1) {|product, n| product * n }
=> 151200

In above example, we have the following elements: a base value 1, an enumerable (5..10), and a block with expressions instructing how to add the calculated value to base value (i.e., multiply the array element to product, where product is initialized with base value)

So the execution follows something like this:

# loop 1
n = 1
product = 1
return value = 1*1

# loop 2
n = 2
product = 1
return value = 1*2

n = 3
product = 2
return value = 2*3

.. As you can notice, the base value is continually updated as the expression loops through the element of container, thus returning the final value of base value as result.

Related