Ruby Inject

As part of my code every day challenge, today I am taking a look at the Ruby Inject method.  I never really understood how the Ruby inject method worked and why one might use it. The  Ruby inject method is useful for aggregating data.  For example a summation could be done with inject (by aggregating each number into the sum.)

Inject seems tricky, but it is not overly complicated once I took a look at a very simple example. Inject takes a code block that contains two arguments and an expression.  The code block is executed for each item in the list, with inject passing each element to the code block of the second argument.  The first argument is the result of the previous execution of the code block.  Since the result doesn’t have a value the first time the code get is executed, you can just pass the initial value as the argument to inject.  If you don’t specify a value to pass, inject will use the first value of the collection as the return value and start iterating at the second collection.  Let’s take a look at inject in action.

a = [9, 7, 5, 3, 1]

a.inject(0) do |sum, num|
 puts "sum: #{sum} num: #{num} sum + i: #{sum + num}"
 sum + num
end

After firing up the IRB console the inject method returned the following output.

sum: 0 num: 9 sum + i: 9
sum: 9 num: 7 sum + i: 16
sum: 16 num: 5 sum + i: 21
sum: 21 num: 3 sum + i: 24
sum: 24 num: 1 sum + i: 25

The inject method returned the same value with this concisely written code.

 

a.inject(0) {|sum, num| sum + num}

This is just one small part of functionality that exists within the Inject Method.

, ,