Skip to content

Instantly share code, notes, and snippets.

@hellosweta
Created May 22, 2017 04:33
Show Gist options
  • Save hellosweta/4e4d9a0c36e0d2b3cdcb2edf3a9a9bad to your computer and use it in GitHub Desktop.
Save hellosweta/4e4d9a0c36e0d2b3cdcb2edf3a9a9bad to your computer and use it in GitHub Desktop.
A method that flattens nested arrays into a 1D array
def my_flatten(array)
flattened_array = []
array.each do |el|
if el.is_a?(Array)
flattened_array.concat(my_flatten(el))
else
flattened_array << el
end
end
flattened_array
end
puts my_flatten([[1,2,[3]],4]) == [1,2,3,4]
puts my_flatten([[1,2,[3]],[4]]) == [1,2,3,4]
puts my_flatten([1,2,3,4]) == [1,2,3,4]
puts my_flatten([1, 2, 3, [4, [5, 6]], [[[7]], 8]]) == [1,2,3,4,5,6,7,8]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment