简体   繁体   中英

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. 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:

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.

So, no option, count just gives a number of items in an array. 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 ".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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