How to Use Reduce in Ruby: Simple Guide with Examples
In Ruby,
reduce is a method that combines all elements of an array into one value by applying a block or symbol operation. You start with an initial value (optional) and then apply the block to accumulate the result step-by-step.Syntax
The reduce method can be used with or without an initial value. It takes a block where you define how to combine elements.
- Without initial value: The first element is used as the initial accumulator.
- With initial value: You provide a starting value for the accumulator.
ruby
array.reduce(initial) { |accumulator, element| block }Example
This example shows how to sum all numbers in an array using reduce. It starts with 0 and adds each element to the accumulator.
ruby
numbers = [1, 2, 3, 4, 5] sum = numbers.reduce(0) { |total, num| total + num } puts sum
Output
15
Common Pitfalls
One common mistake is forgetting the initial value, which can cause unexpected results if the array is empty. Another is mixing up the order of accumulator and element in the block.
Also, using reduce without a block but with a symbol requires careful syntax.
ruby
wrong = [1, 2, 3].reduce { |total, num| total + num } # wrong order correct = [1, 2, 3].reduce { |total, num| total + num } # correct order # Using symbol instead of block sum = [1, 2, 3].reduce(:+) puts sum
Output
6
Quick Reference
| Usage | Description |
|---|---|
| array.reduce { |acc, elem| acc + elem } | Combine elements using block, first element as initial |
| array.reduce(initial) { |acc, elem| acc + elem } | Combine elements starting with initial value |
| array.reduce(:+) | Combine elements using symbol for addition |
| array.reduce(initial, :*) | Combine elements starting with initial using multiplication symbol |
Key Takeaways
Use
reduce to combine array elements into a single value by applying a block or symbol.Always check if you need an initial value to avoid errors with empty arrays.
The block takes two arguments: accumulator and current element, in that order.
You can use symbols like :+ or :* with
reduce for simple operations.Remember the difference between
reduce and inject—they are aliases in Ruby.