Skip to content

Instantly share code, notes, and snippets.

@pablofullana
Created June 25, 2017 22:38
Show Gist options
  • Save pablofullana/a93ff4bf805c918cd227f1d46a0649b5 to your computer and use it in GitHub Desktop.
Save pablofullana/a93ff4bf805c918cd227f1d46a0649b5 to your computer and use it in GitHub Desktop.
Ruby Array#flatten implementation using Enumerable#reduce
require 'awesome_print'
class Array
def flatten_2
reduce([]) do |acc, sub_a|
if sub_a.is_a?(Array)
acc + sub_a.flatten_2
else
acc << sub_a
end
end
end
end
a = [1, 2, [3, 4, [5, 6, [], 7], [8, 9]], 10, 11]
ap a.flatten == a.flatten_2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment