Created
July 17, 2013 12:52
-
-
Save kmazanec/6020317 to your computer and use it in GitHub Desktop.
Flatten an array using a mix of iteration and recursion
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 nil unless array.is_a?(Array) | |
array.each do |item| | |
if item.is_a?(Array) | |
flatten(item).reverse_each do |inner_item| | |
#add to array at index of item | |
array.insert(array.index(item)+1, inner_item) | |
end | |
#remove pre-existing array | |
array.delete(item) | |
end | |
end | |
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