Created
June 2, 2019 08:29
-
-
Save sizief/5dfa2c7ff15ec56a50817d067b8f83c7 to your computer and use it in GitHub Desktop.
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
require 'minitest/autorun' | |
class ArrayTest < Minitest::Test | |
def test_simple_array | |
assert [[1,2,[3]],4].flattify == [1,2,3,4] | |
assert [1,2,[3],4].flattify == [1,2,3,4] | |
assert [[[1],[2]],3,[4]].flattify == [1,2,3,4] | |
assert [['a'],4].flattify == ['a',4] | |
end | |
end | |
class Array | |
#iterate through every element, recurse if it the element is array | |
def flattify | |
puts self.is_a? Array | |
each_with_object([]) do |element, flatten_array| | |
flatten_array.push *(element.is_a?(Array) ? element.flattify : element) | |
end | |
rescue StandardError => e | |
#log e | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment