Created
June 25, 2017 22:38
-
-
Save pablofullana/a93ff4bf805c918cd227f1d46a0649b5 to your computer and use it in GitHub Desktop.
Ruby Array#flatten implementation using Enumerable#reduce
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
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