Skip to content

Instantly share code, notes, and snippets.

@crashtech
Created February 14, 2017 19:53
Show Gist options
  • Save crashtech/1b1d8dd949e9f7f7d88c49adae724b28 to your computer and use it in GitHub Desktop.
Save crashtech/1b1d8dd949e9f7f7d88c49adae724b28 to your computer and use it in GitHub Desktop.
Array flatten
# 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