Ruby #inject behavior differs from documentation

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

# Sum some numbers
(5..10).reduce(:+)                             #=> 45
# Same using a block and inject
(5..10).inject { |sum, n| sum + n }            #=> 45
# Multiply some numbers
(5..10).reduce(1, :*)                          #=> 151200
# Same using a block
(5..10).inject(1) { |product, n| product * n } #=> 151200

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, ?

+4
1

:

a) 1 , ?

1 , apidock:

memo, memo.

, , .

+8

Source: https://habr.com/ru/post/1662356/


All Articles