Skip to content

Instantly share code, notes, and snippets.

@leeacto
Last active December 19, 2015 02:18
Show Gist options
  • Save leeacto/5881764 to your computer and use it in GitHub Desktop.
Save leeacto/5881764 to your computer and use it in GitHub Desktop.
def flatten(array)
a = [] #Must store elements somewhere
array.each do |x| #Go Through each element
if x.class != Array #If the Element is Not an Array
a << x #Store Element in Array 'a'
else
a += flatten(x) #Add flattened array to previous array
end
end
return a #When all elements are non-arrays, return new array filled with non-array elements
end
array = ["bananas", [1,2,3], ["apple", "cheese", [100, 20]], [true], [4.0, 7, 32]]
puts flatten(array).inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment