class Array
def flattify
each_with_object([]) do |element, flattened|
flattened.push *(element.is_a?(Array) ? element.flattify : element)
end
end
end
[1,2,3,4,[1,2,3,4],5].flattify # => [1, 2, 3, 4, 1, 2, 3, 4, 5]
A non-monkey patching
Array
version:
def flattify(array)
array.each_with_object([]) do |element, flattened|
flattened.push *(element.is_a?(Array) ? flattify(element) : element)
end
end
flattify([1,2,3,4,[1,2,3,4],5]) # => [1, 2, 3, 4, 1, 2, 3, 4, 5]