Created
September 19, 2016 07:19
-
-
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
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
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