Created
May 22, 2017 04:33
-
-
Save hellosweta/4e4d9a0c36e0d2b3cdcb2edf3a9a9bad to your computer and use it in GitHub Desktop.
A method that flattens nested arrays into a 1D array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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