Skip to content

Instantly share code, notes, and snippets.

@aybarshazar
Last active March 18, 2017 10:10
Show Gist options
  • Save aybarshazar/d55a1fedf8c6fc4c6c074ec1ae56bee0 to your computer and use it in GitHub Desktop.
Save aybarshazar/d55a1fedf8c6fc4c6c074ec1ae56bee0 to your computer and use it in GitHub Desktop.
def flatten(arr)
result = []
arr.each do |item|
if item.is_a?(Array)
sub_array = flatten(item)
sub_array.each { |sub_item| result << sub_item }
else
result << item
end
end
result
end
flatten([1, 2, 3, 4, 5, 6, 7, 8]) == [1, 2, 3, 4, 5, 6, 7, 8]
flatten([1, 2, [3, [4, 5, 6], 7], 8]) == [1, 2, 3, 4, 5, 6, 7, 8]
flatten([[1, 11], 2, [25, 33, [43, 39], [15], 21], 18]) == [1, 11, 2, 25, 33, 43, 39, 15, 21, 18]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment