Ruby Reduce
The last lesson rebuilt lists into new lists. reduce folds a whole list into one single value.
Reduce adds with an opening value
reduce starts with the opening value 0. The block adds each number into the running total.
numbers = [3, 5, 2]
total = numbers.reduce(0) { |sum, n| sum + n }
puts totalReduce beside sum
The sum method adds an array of numbers directly. reduce reaches the same answer with an explicit block.
numbers = [4, 6, 10]
puts numbers.sum
puts numbers.reduce(0) { |sum, n| sum + n }The longest word by reduce
The running value here is a word, not a number. The block keeps whichever word is longer.
words = ["apple", "fig", "banana", "kiwi"]
longest = words.reduce(words[0]) { |best, w| w.length > best.length ? w : best }
puts longestA total from hash pairs
reduce on a hash hands the block one pair at a time. Each pair holds a key and a value, and pair[1] reads the value.
cart = { "pen" => 3, "book" => 2, "bag" => 5 }
total = cart.reduce(0) { |sum, pair| sum + pair[1] }
puts totalExample
scores = [7, 9, 4, 8]
total = scores.reduce(0) { |sum, s| sum + s }
puts total
puts total / scores.lengthKey points
- reduce combines a list into one value.
- reduce starts from an opening value.
- The block receives the running total and the next item.
- The block result becomes the new running total.
- sum adds numbers without a block.
- reduce also works on the pairs of a hash.
In this example, reduce adds the four scores into the total 28. The program then divides the total by the count of scores. The second printed line is that average, 7.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does [1, 2, 3].reduce(10) { |sum, n| sum + n } return?