Skip to content

Instantly share code, notes, and snippets.

@joseph-lozano
Created November 4, 2018 00:43
Show Gist options
  • Save joseph-lozano/31d850526b070c555d3dd6bf5523ff40 to your computer and use it in GitHub Desktop.
Save joseph-lozano/31d850526b070c555d3dd6bf5523ff40 to your computer and use it in GitHub Desktop.
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