Created
January 15, 2021 22:48
-
-
Save andreleoni/f8f9ccd89c6bfd3447c3fcd015a87edb to your computer and use it in GitHub Desktop.
flatten implementation for ruby
This file contains hidden or 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
input = [[1, 2], 3, 4, 5, [6, 7, [8, [10, 11],9]]] | |
expected = input.dup.flatten | |
class Array | |
def flatten2! | |
self.replace(flatten2) | |
end | |
def flatten2(array = self, result = []) | |
array.each { |a| a.is_a?(Array) ? flatten2(a, result) : result << a } | |
result | |
end | |
end | |
input.flatten2 == expected.flatten |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment