Skip to content

Instantly share code, notes, and snippets.

@arikrak
Created September 9, 2015 19:27
Show Gist options
  • Save arikrak/23bd192a82a870e3c1ef to your computer and use it in GitHub Desktop.
Save arikrak/23bd192a82a870e3c1ef to your computer and use it in GitHub Desktop.
# Flattens an array of arbitrarily nested arrays into a flat array
def flatten(ar)
flat_ar = []
ar.each do |elem|
if elem.class == Array
flat_ar.concat flatten(elem)
else
flat_ar << elem
end
end
return flat_ar
end
# simple 'test cases'
p [] == flatten([])
p [1] == flatten([1])
p [1] == flatten([[[1]]])
p [1,2] == flatten([[1],[2]])
p [1,2,3,4] == flatten([1,[2],[3,[4]]])
p [1,2,3,4] == flatten([[[1],2],3,4])
p [1,2,3,4,5,6,7,8,9,10] == 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