简体   繁体   English

如何有效地获取ruby中嵌套数组中nil元素的数量?

[英]How to get the count of number of nil elements in a nested array in ruby efficiently?

I want the count of the total nil elements in a nested array.我想要嵌套数组中的 nil 元素总数。 I've already come up with a solution.我已经想出了一个解决方案。

chart = [[nil, 'Bob', nil], [nil, nil, 'Bill']]
count = 0

chart.each do |rows|
    rows.each do |eachrow|
        if eachrow == nil
            count += 1
        end
    end
end
count

But, i'd appretiate an even simpler solution.但是,我会欣赏一个更简单的解决方案。

It's simple.这很简单。 First we convert it to a flat array, and then count the number of nil objects on it:首先我们将其转换为平面数组,然后计算其上的 nil 对象的数量:

chart = [[nil, 'Bob', nil], [nil, nil, 'Bill']]

chart.flatten.count(nil)

If you're looking to maintain the integrity of your arrays, then I'd use count.如果您希望保持阵列的完整性,那么我会使用计数。

Count, like to many assumedly flat methods in ruby, can be passed a block or an argument. Count 就像 ruby​​ 中的许多假定的平面方法一样,可以传递一个块或一个参数。

So, no option, count just gives a number of items in an array.所以,别无选择, count 只是给出数组中的一些项目。 With a block, you can find values that equal an amount or any other madness you want to use to determine the truthiness of your match.使用块,您可以找到等于数量的值或您想用来确定匹配真实性的任何其他疯狂值。 But for your case, an argument might be best.但对于你的情况,争论可能是最好的。

chart.map{|c| c.count(nil) } 

Will give you会给你

[2, 2]

It's generally best to avoid creating temporary arrays when that can be avoided, so here I'd write simply:通常最好避免在可以避免的情况下创建临时数组,所以在这里我会简单地写:

chart.sum { |a| a.count(nil) }
  #=> 4

Arguably this also reads well: "sum the number of nil s in each element (array) of chart ".可以说,这也很好读:“对chart每个元素(数组)中的nil数量求和”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM