Created
February 14, 2017 19:53
-
-
Save crashtech/1b1d8dd949e9f7f7d88c49adae724b28 to your computer and use it in GitHub Desktop.
Array flatten
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
# Transform a possible multi-dementional array into one-dimentional array | |
# It returns nil if the giver argument is not an array | |
def flatten(arr) | |
return nil unless arr.is_a?(::Array) | |
# Store the extracted values in the result | |
result = [] | |
# Iterate over the elements appending or merging the parts | |
arr.each do |part| | |
if part.is_a?(::Array) | |
result.concat(flatten(part)) | |
else | |
result << part | |
end | |
end | |
# Return the result | |
result | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment