Reduce / Inject
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 23 of 56.
Sometimes you need to collapse an entire array down to a single value, a sum, a product, a longest string. reduce (also called inject: same method, two names) is the tool.
The block takes two parameters: the accumulator and the current element. The block's return value becomes the next accumulator.
total = [1, 2, 3, 4].reduce(0) { |acc, n| acc + n }
puts total # 10Step by step the accumulator is 0 → 1 → 3 → 6 → 10.
The first argument is the starting value of the accumulator. If you leave it off, Ruby uses the first element of the array:
[1, 2, 3, 4].reduce { |acc, n| acc * n } # 24For pure operations like sum and product, Ruby gives you a shortcut, pass a symbol instead of a block:
[1, 2, 3, 4].reduce(:+) # 10
[1, 2, 3, 4].reduce(:*) # 24Once you can build a custom accumulator, you can compute almost anything in one pass.
Challenge
EasyRead a comma-separated list of integers. Print three lines:
- The sum (use
reduce(:+)) - The product (use
reduce(:*)) - The maximum, computed with
reduceand an explicit block, not usingmax.
For input 2,5,3,8, the output is:
18
240
8Cheat sheet
reduce (alias: inject) collapses an array to a single value. The block receives an accumulator and the current element; its return value becomes the next accumulator.
total = [1, 2, 3, 4].reduce(0) { |acc, n| acc + n } # 10Omit the starting value to use the first element as the initial accumulator:
[1, 2, 3, 4].reduce { |acc, n| acc * n } # 24Pass a symbol as a shortcut for simple operations:
[1, 2, 3, 4].reduce(:+) # 10
[1, 2, 3, 4].reduce(:*) # 24Try it yourself
numbers = gets.chomp.split(",").map(&:to_i)
# TODO: print sum, product, and max (with reduce + explicit block)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier