Skip to content

Instantly share code, notes, and snippets.

@portercar
Created June 29, 2013 20:47
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 portercar/5892605 to your computer and use it in GitHub Desktop.
Save portercar/5892605 to your computer and use it in GitHub Desktop.
Flatten Array Recursively
def flatten(array)
if array.empty?
array
else
element = array.pop
element.kind_of?(Array) ? flatten(array) + flatten(element) : flatten(array) << element
end
end
flatten(["bananas", [1,2,3], ["apple", "cheese", [100, 20]], [true], 'C']) # ["bananas", 1, 2, 3, "apple", "cheese", 100, 20, true, "C"]
flatten([['A','B'],'C']) # ["A", "B", "C"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment