Stefan Hansch
Stefan Hansch

Reputation: 1590

How check in ruby if nested array is empty?

Response list returns empty nested array: [[], [], []]

How better test with ruby that following nested array is empty?

Upvotes: 2

Views: 324

Answers (2)

Simon
Simon

Reputation: 25984

If you want to handle deeply nested arrays, you probably want to flatten your array first:

[[], [], []].flatten.empty?
=> true

[[], [[], [[]]]].flatten.empty?
=> true

[[], [[], [[1]]]].flatten.empty?
=> false

Upvotes: 3

mechnicov
mechnicov

Reputation: 15248

You can use Array#empty?

To check all nested arrays are empty with Array#all?

[[], [], []].all?(&:empty?)
# => true

[[1], [2], []].all?(&:empty?)
# => false

[[1], [2], [3]].all?(&:empty?)
# => false

To check at least one nested is empty with Array#any?

[[], [], []].any?(&:empty?)
# => true

[[1], [2], []].any?(&:empty?)
# => true

[[1], [2], [3]].any?(&:empty?)
# => false

Upvotes: 4

Related Questions