Last active
January 21, 2017 14:47
-
-
Save niteshpurohit/a8445f51f0548fd4cd4121350ee52477 to your computer and use it in GitHub Desktop.
Flatten Array with using inbuilt method
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
class Array #class so that this method is available for array. monkey patching | |
def flat_it | |
each_with_object([]) do |element, flattened| #traverse each element | |
flattened.push *(element.is_a?(Array) ? element.flat_it : element) #call method if Array, push to flattened if not array | |
end | |
end | |
end | |
#usage | |
[1,2,3,4,[1,2,3,4,[1,2,[44,34]]],5].flat_it | |
#output | |
#[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 44, 34, 5] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment