Skip to content

Instantly share code, notes, and snippets.

@rgalindo33
Created September 19, 2016 07:19
Show Gist options
  • Save rgalindo33/2bc057b91f22bfd99447d4b7d96c995b to your computer and use it in GitHub Desktop.
Save rgalindo33/2bc057b91f22bfd99447d4b7d96c995b to your computer and use it in GitHub Desktop.
flatten an array of arbitrarily nested arrays of integers into a flat array of integers
require 'minitest/autorun'
class CustomFlattenTest < MiniTest::Test
def test_custom_flatten
assert_equal [1,2,3,4], [[1,2,[3]],4].custom_flatten
end
end
module ArrayExtensions
def custom_flatten
inject(Array.new) do |flat_array, element|
flat_array + Array(element.is_a?(Array) ? element.custom_flatten : element)
end
end
end
Array.send :include, ArrayExtensions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment