加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby #inject行为与文档不同

发布时间:2020-12-17 03:42:43 所属栏目:百科 来源:网络整理
导读:看看 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 } #
看看 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作为初始值包含在实际上不需要时?

从apidock开始,inject不接受1作为初始值:

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.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读