Menu
Coddy logo textTech

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   # 10

Step 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 }   # 24

For 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(:*)   # 24

Once you can build a custom accumulator, you can compute almost anything in one pass.

challenge icon

Challenge

Easy

Read a comma-separated list of integers. Print three lines:

  1. The sum (use reduce(:+))
  2. The product (use reduce(:*))
  3. The maximum, computed with reduce and an explicit block, not using max.

For input 2,5,3,8, the output is:

18
240
8

Cheat 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 }  # 10

Omit the starting value to use the first element as the initial accumulator:

[1, 2, 3, 4].reduce { |acc, n| acc * n }  # 24

Pass a symbol as a shortcut for simple operations:

[1, 2, 3, 4].reduce(:+)  # 10
[1, 2, 3, 4].reduce(:*)  # 24

Try it yourself

numbers = gets.chomp.split(",").map(&:to_i)

# TODO: print sum, product, and max (with reduce + explicit block)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow