Andrew Schwartz Andrew Schwartz - 2 years ago 110
Ruby Question

Ruby inner flatten (array of arrays)

I have an array like the following

[[0, :a], [2, :b]],
[3, :c],
[4, :d],
[[5, :e], [6, :f], [7, :g]]

That is, an Array of elements that are either (1) 2-element Arrays, or (2) an Array of 2-element Arrays.

I am trying to find an elegant way to "flatten" this array such that elements that are (2) get expanded out into root-level elements. In this example:

[[0, :a], [2, :b], [3, :c], [4, :d], [5, :e], [6, :f], [7, :g]]

This is almost like using
, except
needs to work from the inside out, rather than the outside in.

The actual arrays can get very large, so I do not want to push (
) elements onto a new Array in a loop for performance reasons. For some reason I cannot think of how to use any combination of
, or other more efficient
methods to accomplish this without writing a C++-style preallocate-and-populate loop. Can anyone think of a more Rubyist way to do this?

Answer Source

One way to do is:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download