Skip to content

Instantly share code, notes, and snippets.

@ahazem
Created January 15, 2016 10:40
Show Gist options
  • Save ahazem/21eeb655b85af166bddc to your computer and use it in GitHub Desktop.
Save ahazem/21eeb655b85af166bddc to your computer and use it in GitHub Desktop.
A simple implementation of the flatten method
# Turn arbitrarily nested arrays into a flat one.
# Example: [[1,2,[3]],4] -> [1,2,3,4]
def flatten(array)
result = []
array.each do |element|
if element.is_a?(Array)
result.concat(flatten(element))
else
result << element
end
end
result
end
p flatten([[1,2,[3]],4, [5,6,[7],[8,9]],10])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment