reduce and each_with_object
Aggregate collections.
What Is reduce?
reduce (alias inject) combines all elements into a single value. The block receives an accumulator and the current element.
sum = [1, 2, 3, 4].reduce(0) { |acc, n| acc + n }
puts sumHow the Accumulator Works
The accumulator carries the running result between iterations. Whatever the block returns becomes the next accumulator.
[1, 2, 3].reduce(0) do |acc, n|
puts "acc=#{acc} n=#{n}"
acc + n
endAll lessons in this course
- Creating Ranges
- The Enumerable Module
- map, select, reject
- reduce and each_with_object