reduce / inject (Ruby)
reduce (alias inject) combines all elements of a collection into a single value by repeatedly applying a block, carrying an accumulator. It's used for sums, products, and other aggregations.
Ruby
reduce threads an accumulator through every element: you give a starting value and a block (acc, element) -> new_acc, and it folds the collection down to one result. [1,2,3].reduce(0) { |sum, n| sum + n } yields 6. Omit the initial value and the first element becomes the accumulator's start.
For simple binary operators there's a symbol shortcut: [1,2,3,4].reduce(:+) sums, reduce(:*) multiplies. This makes common aggregations a one-liner.
reduce is the most general Enumerable method — map, select, and even count can be expressed in terms of it. Reach for it when you need a custom aggregation that the more specialized methods (sum, max, count) don't directly provide.
Syntax
collection.reduce(initial) { |acc, item| ... }
collection.reduce(:+)Examples
Ruby
puts [1, 2, 3, 4].reduce(:+)
puts [1, 2, 3, 4].reduce(1) { |product, n| product * n }
words = ["a", "b", "c"]
puts words.reduce("") { |s, w| s + w }Output:
10
24
abc