# I have a recursive method that aggregates data in the form of
# 2-dimensional arrays.
# The problem is at the top of the recursion call, I ended up with
# multi-dimensional arrays which depend
# on how deep the recursion is.
# What is the best way to flatten multi-dimensional arrays back into
# 2-dimensional arrays?
# the data might look like this:
# [ [a, b, c], [ [ [d, e], [f, g] ], [h, i] ]
# and I would like to be flatten into:
# [ [a, b, c], [d, e], [f, g], [h, i] ]
you can also recurse it back 
eg,
a = [[:a, :b, :c], [[[:d, :e], [:f, :g]], [:h, :i]]]
#=> [[:a, :b, :c], [[[:d, :e], [:f, :g]], [:h, :i]]]
class Array
def flat2
a=[]
self.each { |e| a += ( e == e.flatten ? [e] : e.flat2 ) }
a
end
end
#=> nil
p a.flat2
[[:a, :b, :c], [:d, :e], [:f, :g], [:h, :i]]
#=> nil
of course, the better way is to not perform this (back) recursing at all by reexamining your first recurs algo (as suggested by Ed B)
kind regards -botp
···
From: Wirianto Djunaidi [mailto:wirianto.djunaidi@gmail.com]