Home > Back-end >  How check in ruby if nested array is empty?
How check in ruby if nested array is empty?

Time:10-05

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

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

CodePudding user response:

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

CodePudding user response:

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
  •  Tags:  
  • ruby
  • Related