Looking at the Ruby documentation in the class,Enumerable I noticed something interesting, and I would like to know why this happens.
In the description, I found the following examples: #inject
(5..10).reduce(:+)
(5..10).inject { |sum, n| sum + n }
(5..10).reduce(1, :*)
(5..10).inject(1) { |product, n| product * n }
Note that when #injectused for multiplication, it gets an initial value of 1. I thought it was necessary, because otherwise the product will get 0 as an initial value (as it happens in total), and the multiplication will also be 0. Actually, if I launched
p (1..5).inject(0) { |prod, n| prod * n }
I got
0
But then I ran
p (1..5).inject { |sum, n| sum + n }
p (1..5).inject { |prod, n| prod * n }
and received
15
120
My questions:
a) Why does the documentation include this value 1 as an initial value when it is not really needed?
and
b) #inject, ?