Skip to content

Instantly share code, notes, and snippets.

@tlemburg
Created March 31, 2020 23:11
Show Gist options
  • Save tlemburg/b1b7dd855061b4411d2f90edb455d4d8 to your computer and use it in GitHub Desktop.
Save tlemburg/b1b7dd855061b4411d2f90edb455d4d8 to your computer and use it in GitHub Desktop.
def flatten(array)
new_arr = []
array.each do |item|
if item.is_a?(Array)
flatten(item).each do |inner|
new_arr << inner
end
else
new_arr << item
end
end
return new_arr
end
puts flatten([[1,2,[3]],4]).inspect
#=> [1, 2, 3, 4]
puts flatten([[[[1,2],[3,4],[5,6],[7]]]]).inspect
#=> [1, 2, 3, 4, 5, 6, 7]
puts flatten([]).inspect
#=> []
puts flatten([[[[[[[[[[[1]]]]]]]]]]]).inspect
#=> [1]
puts flatten([3,4,5,6]).inspect
#=> [3, 4, 5, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment