Last Updated: February 25, 2016
·
723
· drewsamsen

Recursively flatten an array

I was asked this recently during a phone interview and, in my nervousness, struggled to come up with something elegant.

Afterwards, I quickly banged this out (of course, stupid brain):

# Goal: recursively flatten array
# flatten([[1, [], [2, 3]], [[[[4]]]], 5]) # => [1, 2, 3, 4, 5]

def flatten(array, flattened = Array.new)
  array.each_with_index do |elem, i|
    if elem.is_a?(Array)
      flatten(elem, flattened)
    else
      flattened << elem
    end
  end
  flattened
end

puts flatten([[1, [], [2, 3]], [[[[4]]]], 5])
# => [1, 2, 3, 4, 5]