Created
November 4, 2018 00:43
-
-
Save joseph-lozano/31d850526b070c555d3dd6bf5523ff40 to your computer and use it in GitHub Desktop.
This file contains 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(arr, output = []) | |
raise "Input must be array. Usage: flatten(arr)" unless arr.class == Array | |
arr.each do |el| | |
if el.class == Array | |
flatten(el, output) | |
else | |
output << el | |
end | |
end | |
output | |
end | |
# Examples | |
# > flatten([]) | |
# => [] | |
# > flatten([1]) | |
# => [1] | |
# > flatten([1, 2]) | |
# => [1, 2] | |
# > flatten([1, [2]]) | |
# => [1, 2] | |
# > flatten([[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10]) | |
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] | |
# > flatten([[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10, [[[[[11]]]]]]) | |
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment