Brand
Brand

Reputation: 1701

remove "empty" elements from multidimensional array

I have a multidimensional array something like this

[ [[]], [[1], [2]], [[1, 2]] ]

What's the best way to remove the empty array?

Right now I am just doing a array[1..-1] to remove the first element but I would like a more reliable way to do it.

Upvotes: 4

Views: 4007

Answers (1)

Douglas F Shearer
Douglas F Shearer

Reputation: 26488

Flatten each array and if it has no elements in it, delete it.

arr = [ [[]], [[1], [2]], [[1, 2]] ]
arr = arr.delete_if { |elem| elem.flatten.empty? }
# => [[[1], [2]], [[1, 2]]]

Upvotes: 8

Related Questions