Created
August 19, 2019 09:42
-
-
Save Henryvw/359fd4314f39452e4b2e860383129784 to your computer and use it in GitHub Desktop.
Recursively Flatten an Array
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 recursive_flatten(incoming_array, new_flattened_array = []) | |
incoming_array.each do |item| | |
if item.class == Array | |
# Recursion | |
recursive_flatten(item, new_flattened_array) | |
else | |
new_flattened_array << item | |
end | |
end | |
new_flattened_array | |
end | |
henrys_array = [[5,6],1,2,3,[2,[3,4],4]] | |
puts recursive_flatten(henrys_array) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment