Created
November 7, 2016 20:05
-
-
Save marktellez/0ebc9714ed44df60633cc8c12c6f2461 to your computer and use it in GitHub Desktop.
Flattening an array in ruby is easy too! Your friend again is splat and recursion
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
# I dont like to monkey-patch, so I dont add this to Array | |
# also, this method allows for lazy eval, something you cant | |
# do if you bind this to an array! | |
def flatten(arr, depth=Float::INFINITY) | |
return arr if depth.zero? | |
return arr.reduce([]) do |acc, v| | |
if v.kind_of?(Array) | |
acc.push(*flatten(v, depth-1)) | |
else | |
acc.push v | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment