Created
March 31, 2020 23:11
-
-
Save tlemburg/b1b7dd855061b4411d2f90edb455d4d8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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