The doc for those two methods is a bit unclear, therfore an example is better than thousands words.
Let’s start with an example without argument to the #reduce
method.
list = (1..5).to_a
result = list.reduce do |sum, n|
sum + n
end
puts result # 15
In this case, #reduce
will pass the first element of the array (1
) to the first argument (sum
) and the second element (2
) to the second argument (n
).
The block execution then kicks in and return 1 + 2 = 3
.
In the next iteration, that 3
will become the value of sum
and the next element of the array (here, 3
) will become the value of n
.
The block execution then kicks in and return 3 + 3 = 6
.
And so on until the end of the array.
Example with one numerical argument
list = (1..5).to_a
result = list.reduce(6) do |sum, n|
sum + n
end
puts result # 21
The only difference here is the first element passed to sum
is not the first element of the array list
, but the argument 6
instead. The first element of the array (1
) is passed to n
.
In this scenario, when the block execution kicks in for the first time, it returns 6 + 1 = 7
.
Example with one symbol argument
list = (1..5).to_a
result = list.reduce(:*)
puts result # 120
In this case, #reduce
will perform a multiplication istead of an addition.
The result will be 1 * 2 * 3 * 4 * 5 = 120
.
It is possible to add a first numerical argument as well.