Last active
June 27, 2019 09:29
-
-
Save bernardobarreto/4d62adf9aa21d7558d8ca3dc73e77f44 to your computer and use it in GitHub Desktop.
ruby array flatten example
This file contains 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 flatten(array) | |
result = [] | |
array.each do |element| | |
if element.class == Array | |
flatten(element).each do |sub| | |
result << sub | |
end | |
else | |
result << element | |
end | |
end | |
result | |
end | |
puts flatten([[1,2,[3]],4]) #=> [1,2,3,4] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment