0
0
Rubyprogramming~5 mins

Reduce/inject for accumulation in Ruby

Choose your learning style9 modes available
Introduction

Reduce (also called inject) helps you combine all items in a list into one value, like adding numbers or joining words.

When you want to add all numbers in a list to get a total.
When you want to multiply all numbers together to get a product.
When you want to join all words in an array into a sentence.
When you want to find the biggest or smallest number in a list.
When you want to combine data from many items into one result.
Syntax
Ruby
array.reduce(initial_value) { |accumulator, item| 
  # combine accumulator and item
}

# or using inject (same as reduce)
array.inject(initial_value) { |accumulator, item| 
  # combine accumulator and item
}

The accumulator starts with initial_value and updates with each item.

You can omit initial_value, then the first item is used as the start.

Examples
Adds all numbers starting from 0, result is 10.
Ruby
[1, 2, 3, 4].reduce(0) { |sum, n| sum + n }
Multiplies all numbers starting from 1, result is 24.
Ruby
[1, 2, 3, 4].inject(1) { |product, n| product * n }
Joins all letters into "abc" starting from empty string.
Ruby
["a", "b", "c"].reduce("") { |str, ch| str + ch }
Finds the biggest number without initial value, result is 8.
Ruby
[5, 3, 8, 2].reduce { |max, n| n > max ? n : max }
Sample Program

This program shows how to add numbers, multiply them, join words, and find the biggest number using reduce/inject.

Ruby
numbers = [10, 20, 30, 40]
sum = numbers.reduce(0) { |total, num| total + num }
product = numbers.inject(1) { |total, num| total * num }
words = ["Ruby", " ", "is", " ", "fun"]
sentence = words.reduce("") { |str, word| str + word }
max_num = numbers.reduce { |max, num| num > max ? num : max }

puts "Sum: #{sum}"
puts "Product: #{product}"
puts "Sentence: '#{sentence}'"
puts "Max number: #{max_num}"
OutputSuccess
Important Notes

Reduce and inject are the same method; you can use either name.

Always think about what your starting value (initial_value) should be.

If you forget the initial value, the first item is used as the start, so the block runs one less time.

Summary

Reduce/inject combines all items in a list into one value.

You provide a starting value and a block to tell how to combine.

It works great for sums, products, joining strings, or finding max/min.