Skip to content

Instantly share code, notes, and snippets.

@niteshpurohit
Last active January 21, 2017 14:47
Show Gist options
  • Save niteshpurohit/a8445f51f0548fd4cd4121350ee52477 to your computer and use it in GitHub Desktop.
Save niteshpurohit/a8445f51f0548fd4cd4121350ee52477 to your computer and use it in GitHub Desktop.
Flatten Array with using inbuilt method
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