gpt4 book ai didi

ruby - 如果 block 从不更改累加器,为什么 reduce 不返回初始值?

转载 作者:数据小太阳 更新时间:2023-10-29 08:43:03 25 4
gpt4 key购买 nike

考虑以下 irb 循环:

irb(main):015:0> [nil, nil].reduce(0) { |accum, x| accum + 1 unless x.nil? }
=> nil

为什么返回 nil 而不是 0

根据 Ruby Enumerable 文档:

If you specify a block, then for each element in enum the block is passed an accumulator value (memo) and the element. If you specify a symbol instead, then each element in the collection will be passed to the named method of memo. In either case, the result becomes the new value for memo. At the end of the iteration, the final value of memo is the return value for the method.

我的期望是累加器应该在数组开始折叠之前设置为 0,因为这是作为初始值给出的。然后, block 的转义子句将触发此数组中的所有元素,因此累加器永远不会改变。最后,由于 0 是为累加器存储的最后一个值,因此应该返回它。

最佳答案

无论 block 返回什么,都将成为下一个累加器值。

然后你返回nil:

'whatever' unless true #=> nil

你可以这样做:

arr.reduce(0) { |a, e| e.nil? ? a : a + 1 }

或者这个:

arr.compact.reduce(0) { |a, e| a + 1 }

或者这个:

arr.compact.size

关于ruby - 如果 block 从不更改累加器,为什么 reduce 不返回初始值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46392017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com