Skip to content

Instantly share code, notes, and snippets.

@ydaniju
Last active January 1, 2018 17:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ydaniju/4542a8a1d8266ebc6b588178d58c1a2d to your computer and use it in GitHub Desktop.
Save ydaniju/4542a8a1d8266ebc6b588178d58c1a2d to your computer and use it in GitHub Desktop.
Another implementation for Array.flatten
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