Reduce vs Each With Object
Both methods serve the same purpose : from an Enumerator create a single value out of it
Reduce
Reduce is prefered when you need to produce a simple value because it reduce over the returned value
[1, 2, 3].reduce(:+)
> 3
We can illustrate this simply with this snippet :
[1, 2, 3].reduce do |acc, v|
acc += v
0
end
> 0
Each With Object
Each with object is prefered when you reduce on a hash or some sort of complex object beacause is use the accumulator value and not the returned one
[1, 2, 3].each_with_object({ sum: 0 }) do |v, acc|
acc[:sum] += v
0
end
> {sum: 6}
Fun fact, reduce
takes |acc, v|
while each_with_object
take |v, acc|