0Pricing
Ruby Academy · Lesson

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 sum

How 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
end

All lessons in this course

  1. Creating Ranges
  2. The Enumerable Module
  3. map, select, reject
  4. reduce and each_with_object
← Back to Ruby Academy