How to Reduce an Array in Ruby: Syntax and Examples
In Ruby, you can use the
reduce method to combine all elements of an array into a single value by applying a block or symbol operation. It takes an optional initial value and a block that specifies how to combine elements step-by-step.Syntax
The reduce method is called on an array and can take an optional initial value and a block or a symbol representing the operation.
array.reduce(initial) { |accumulator, element| ... }: Combines elements starting withinitial.array.reduce { |accumulator, element| ... }: Combines elements starting with the first element as the initial accumulator.array.reduce(:operation): Uses a symbol like:+to specify the operation.
ruby
array.reduce(initial) { |accumulator, element| block } array.reduce { |accumulator, element| block } array.reduce(:operation)
Example
This example shows how to sum all numbers in an array using reduce with and without an initial value, and how to multiply all elements.
ruby
numbers = [2, 4, 6] # Sum without initial value sum1 = numbers.reduce { |acc, n| acc + n } # Sum with initial value 10 sum2 = numbers.reduce(10) { |acc, n| acc + n } # Multiply all elements product = numbers.reduce(1, :*) puts "Sum without initial: #{sum1}" puts "Sum with initial 10: #{sum2}" puts "Product of elements: #{product}"
Output
Sum without initial: 12
Sum with initial 10: 22
Product of elements: 48
Common Pitfalls
One common mistake is forgetting the initial value when the array might be empty, which can cause errors or unexpected results. Another is mixing up the order of parameters in the block, which changes how elements combine.
Also, using reduce without a block or symbol will raise an error.
ruby
numbers = [] # This will raise an error because no initial value is given # sum = numbers.reduce { |acc, n| acc + n } # Error # Correct way: provide an initial value sum = numbers.reduce(0) { |acc, n| acc + n } puts "Sum with initial on empty array: #{sum}"
Output
Sum with initial on empty array: 0
Quick Reference
| Usage | Description | Example |
|---|---|---|
| array.reduce { |acc, el| ... } | Combine elements using block, first element as initial | [1,2,3].reduce { |acc, n| acc + n } #=> 6 |
| array.reduce(initial) { |acc, el| ... } | Combine elements starting with initial value | [1,2,3].reduce(10) { |acc, n| acc + n } #=> 16 |
| array.reduce(:symbol) | Combine elements using symbol operation | [1,2,3,4].reduce(:*) #=> 24 |
| array.reduce(initial, :symbol) | Combine elements starting with initial using symbol | [1,2,3].reduce(2, :*) #=> 12 |
Key Takeaways
Use
reduce to combine array elements into one value with a block or symbol.Always provide an initial value if the array might be empty to avoid errors.
The block takes two parameters: accumulator and current element, in that order.
You can use symbols like
:+ or :* for common operations.Without a block or symbol,
reduce will raise an error.