Skip to content

Instantly share code, notes, and snippets.

@marktellez
Created November 7, 2016 20:05
Show Gist options
  • Save marktellez/0ebc9714ed44df60633cc8c12c6f2461 to your computer and use it in GitHub Desktop.
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
# 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