Hommer Smith
Hommer Smith

Reputation: 27852

Find number of arrays in an array which are not empty

I have an array of arrays like this:

[row1, row2, row3]

I need to find how many of those rows are not empty (have some object inside). I know I can do row1.any?, but how would I find how many of those are in the array?

Upvotes: 1

Views: 52

Answers (3)

hirolau
hirolau

Reputation: 13901

And as usual, remember that .any? will not give you a hit if you array is filled with false or nil.

[[false], [nil], [true], []].count &:any? #=> 1 only one non-empty (true)

Perhaps it is better to do:

[[false], [nil], [true], []].reject(&:empty?).count #=> 3 non-empty (true, nil, false)

Upvotes: 0

Matt
Matt

Reputation: 20786

Use the block form of Array#count:

[row1, row2, row3].count &:any?

Upvotes: 5

Nobita
Nobita

Reputation: 23713

What about this?

[row1,row2,row3].select { |arr| arr.any? }.size

You select just the objects (arrays) which have any elements, and then calculate the size of that resulting Array.

Upvotes: 3

Related Questions