Ruby #inject 行为与文档不同

Ruby #inject behavior is different from documentation

看看 Ruby documentation on Enumerable class 我发现了一些有趣的事情,我想知道为什么会这样。

#inject description 我找到了这些例子:

# 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

请注意,当 #inject 用于乘法时,它接收到初始值 1。我认为这是必要的,因为否则乘积将接收 0 作为起始值(就像在求和中发生的那样)和乘法也为 0。事实上,如果我 运行

p (1..5).inject(0) { |prod, n| prod * n } 

我得到了

0

但是后来我运行

p (1..5).inject { |sum, n| sum + n } 
p (1..5).inject { |prod, n| prod * n } 

得到了

15
120

我的问题是:

a) 为什么文档将这个 1 作为初始值,而实际上并不需要它?

b) #inject 在初始化被注入对象时的行为是什么?

回答你的第一个问题:

a) 为什么文档将这个 1 作为初始值,而实际上并不需要它?

inject不以1为初始值,来自apidock:

If you do not explicitly specify an initial value for memo, then uses the first element of collection is used as the initial value of memo.

第二个问题的答案在于第一个问题本身的答案,因为它将对象初始化为应用注入的数组的第一个元素。