liveBook · Manning

Reduction operation

As explained in The Well-Grounded Rubyist, Fourth Edition

inject, also known as reduce, is an Enumerable method that combines collection elements through an accumulator and a block, optionally starting with an initial value.

Ruby’s Enumerable methods inject and reduce combine a collection’s elements through an accumulator. Each block result becomes the accumulator for the next element; the final result is returned. section 10.5.6

Sum an array

With an initial value of 0, each iteration adds the next number to the accumulator, yielding 10. section 10.5.6

>> [1,2,3,4].inject(0) {|acc,n| acc + n }
=> 10

The block receives the running total and the next element. section 10.5.6

If no initial value is given, inject uses the first element as the accumulator and starts yielding elements from the second. Passing a symbol such as :+ uses that method for the reduction. section 10.5.6

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

A symbol can replace the block when the reduction simply calls one method on the accumulator and each element. section 10.5.6

Reduction can aggregate an Enumerable directly, including a File object, avoiding an intermediate array. It can also replace a mutating loop: reducing an array without modifying it allows a summing method to be called repeatedly with the same input. section 12.2.8 section 16.1.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains accumulator initialization, iteration, final return values, and symbol shorthand through a worked sum.
Examples
Uses an array sum, symbol shorthand, and direct File reduction to calculate an average.
What it assumes
Assumes familiarity with collections and blocks while explaining accumulator behavior from iteration onward.
What you can do after
Apply inject or reduce to aggregate collections without mutating the input.
How it connects
Connects Enumerable and blocks with accumulators, File iteration, and side effects.

Also explained in

Compare how 9 books explain reduction operation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.