Last active
December 19, 2015 21:29
-
-
Save kmazanec/6020325 to your computer and use it in GitHub Desktop.
Flatten an array entirely using recursion. (I am particularly amazed at how short and simple this is compared to using iteration)
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(array) | |
return Array(array) unless array.is_a?(Array) && array.length > 0 | |
flatten(array.shift) + flatten(array) | |
end | |
array = ["bananas", [1,2,3], ["apple", "cheese", [100, 20]], [true], [4.0, 7, 32]] | |
puts flatten(array).to_s | |
array = ["bananas"] | |
puts flatten(array).to_s | |
array = "bananas" | |
puts flatten(array).to_s | |
array = [[["bananas"], nil]] | |
puts flatten(array).to_s | |
array = nil.to_a | |
puts flatten(array).to_s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment