Created
January 15, 2016 10:40
-
-
Save ahazem/21eeb655b85af166bddc to your computer and use it in GitHub Desktop.
A simple implementation of the flatten method
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
# Turn arbitrarily nested arrays into a flat one. | |
# Example: [[1,2,[3]],4] -> [1,2,3,4] | |
def flatten(array) | |
result = [] | |
array.each do |element| | |
if element.is_a?(Array) | |
result.concat(flatten(element)) | |
else | |
result << element | |
end | |
end | |
result | |
end | |
p 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