减少总和返回零 [英] Reduce returns nil on summation

查看:51
本文介绍了减少总和返回零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在计算一个项目在枚举中出现的次数.

I'm counting the number of times an item appears in an Enumeration.

irb(main):003:0> (1..3).reduce(0) {|sum, p| sum += 1 if p == 1}
=> nil
irb(main):004:0> (1..3).find_all{|p| p == 1}.length
=> 1

reduce 方法似乎应该与 find_all 方法具有相同的行为.为什么它返回 nil 而不是 1?

The reduce method seems like it should have the same behaviour as the find_all method. Why does it return nil instead of 1?

irb(main):023:0> (1..3).reduce(0) {|sum, p| sum += 1 if p == 2}
NoMethodError: undefined method `+' for nil:NilClass
    from (irb):23:in `block in irb_binding'
    from (irb):23:in `each'
    from (irb):23:in `reduce'
    from (irb):23
    from /usr/bin/irb:12:in `<main>'

在第一次迭代中出了点问题.可以不这样使用reduce吗?

Something is going wrong in the first iteration. Can reduce just not be used this way?

推荐答案

在reduce中,块中代码的值被赋值给累加器.在您的情况下,您将第一个分配覆盖为与后面的 nils 相加.

In reduce, the value of the code in the block is assigned to the accumulator. In your case you override the first assignment to sum with later nils.

您可以通过以下方式解决此问题:

You can fix this by:

(1..3).reduce(0) {|sum, p| sum += 1 if p == 1; sum}

(1..3).reduce(0) {|sum, p| sum += p == 1 ? 1 : 0}

对于您的第二个示例,sum 在第一次迭代时被赋值为 nil,而您正试图在第二次迭代时将 1 添加到 nil.

For your second example, sum is assigned nil on the first iteration, and you are trying to add 1 to nil on the second.

请记住,reduce/inject 可能不是最好的计数工具 - 试试

Please keep in mind that reduce/inject is probably not the best instrument for counting - try

(1..3).count(1)

这篇关于减少总和返回零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆