Last active
January 1, 2018 17:10
-
-
Save ydaniju/4542a8a1d8266ebc6b588178d58c1a2d to your computer and use it in GitHub Desktop.
Another implementation for Array.flatten
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 deflate(arr, container = []) | |
arr.each do |a| | |
push(a, container) | |
end | |
container | |
end | |
def push(a, container) | |
if a.is_a? Integer | |
container << a | |
else | |
deflate(a, container) | |
end | |
end | |
p deflate([1, 2, 3]) # [1, 2, 3] | |
p deflate([[1], [2, 3, 4], 2, 3]) # [1, 2, 3, 2, 3] | |
p deflate([1, 2, 3, [4, 5]]) # [1, 2, 3, 4, 5] | |
p deflate([1, 2, 3, [4, 5, [1]]]) # [1, 2, 3, 4, 5, 1] | |
p deflate([1, 2, 3, [4, 5, [1]], [9, 10], [11, 12, [13]]]) # [1, 2, 3, 4, 5, 1, 9, 10, 11, 12, 13] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment