Last active
September 6, 2016 01:08
-
-
Save MaxPleaner/8c746e4dd0ec1c732085e889331b3c07 to your computer and use it in GitHub Desktop.
recursive Array#flatten
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
class MyArray < Array | |
def flatten | |
reduce [] do |memo, item| | |
memo.concat item.is_a?(Array) ? MyArray.new(item).flatten : [item] | |
end | |
end | |
end | |
test_arr = MyArray.new [ 1, [ 1 ], [ 1, [ 1 ] ] ] | |
print test_arr.flatten | |
# => [1,1,1,1] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment