liveBook · Manning

Accumulator

As explained in The Well-Grounded Rubyist, Fourth Edition

An accumulator is a value carried across iterations and replaced by each iteration's calculated result.

An accumulator carries a value across iterations: each pass calculates a result, replaces the accumulator with it, and makes that value available to the next pass. In `inject`, an initial value can be supplied; otherwise, the first collection element initializes the accumulator. The last result becomes the method’s return value. section 10.5.6

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

Adding each element to the carried total shows the accumulator changing on every iteration. section 10.5.6

An accumulator can also collect results rather than build a single value. A `map` implementation stores each block’s return value in an accumulator array and returns that array. Unlike `each`, which discards block return values, `map` uses them; a block that calls `puts` therefore contributes `nil` for each iteration. section 6.3.7 section 10.6.1

class Array
  # Put the definition of my_each here
  def my_map
    acc = []
    my_each {|e| acc << yield(e) }
    acc
  end
end

This implementation builds `map` on `my_each`, appending each block result before returning the accumulated array. section 6.3.7

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Traces initialization, replacement, and final return in inject, then shows accumulator-array construction for map.
Examples
Uses a four-number sum and a name-uppercasing map, including a map block whose puts calls yield nil results.
What you can do after
Build it from scratch by accumulating block results in a my_map method, or apply it with inject to reduce values.
How it connects
Connects accumulators to inject/reduce, Enumerable, map, each, and block return values.

Also explained in

Compare how 4 books explain accumulator →

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.