4

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.

4
  • What do you want to do with [ [[],[1]], [[1],[2]] ]? Commented Oct 25, 2011 at 17:08
  • @muistooshort note that your array is different from mine. i'll be comparing it against other arrays to find the shortest substring. i'm getting this by doing something like ar.each_index.map{ |i| ar.combination(i).to_a Commented Oct 26, 2011 at 1:19
  • So you're saying that you can't get [[],[1]] as an element? I'm just trying to clarify what your data really looks like. Commented Oct 26, 2011 at 1:37
  • @muistooshort yep, can't get [[], [1]]. but you can get [ [[]], [[1], [2]] ] for example. Commented Oct 26, 2011 at 6:54

1 Answer 1

8

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]]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.