Array#reduce

reduce(initial = nil) { |memo, element| block } -> result
Returns: Object · Updated March 13, 2026 · Array Methods
arrays enumerable accumulation fold

reduce is an alias for inject. It iterates over an array while maintaining an accumulator value. On each iteration, the block receives the current accumulator (called memo) and the current element. The block return value becomes the new accumulator. After processing all elements, reduce returns the final accumulator value.

Syntax

array.reduce(initial) { |memo, element| block }
array.reduce { |memo, element| block }

Parameters

ParameterTypeDefaultDescription
initialObjectnilStarting value for the accumulator. If omitted, the first element becomes the initial accumulator.

Examples

Summing numbers

numbers = [1, 2, 3, 4, 5]

sum = numbers.reduce(0) { |memo, n| memo + n }
puts sum  # => 15

sum = numbers.reduce { |memo, n| memo + n }
puts sum  # => 15

Building a hash

items = [:a, :b, :c]

indexed = items.reduce({}) do |memo, item|
  memo[item] = item.to_s.upcase
  memo
end
puts indexed  # => {:a=>"A", :b=>"B", :c=>"C"}

Using symbol shorthand

# Concatenate strings
words = ["Hello", "World", "!"].reduce(:+)
puts words  # => "HelloWorld!"

# Multiply all elements
product = [2, 3, 4, 5].reduce(:*)
puts product  # => 120

Common Patterns

# Start from different initial value
result = [1, 2, 3].reduce(10) { |memo, n| memo + n }
puts result  # => 16

# Chaining
result = [1, 2, 3, 4, 5, 6]
  .select(&:even?)
  .map { |n| n * 2 }
  .reduce(0) { |memo, n| memo + n }
puts result  # => 24

Errors

# Empty without initial returns nil
[].reduce { |m, e| m + e }  # => nil

# Empty with initial returns initial
[].reduce(0) { |m, e| m + e }  # => 0

See Also