Skip to content

Instantly share code, notes, and snippets.

@sizief
Created June 2, 2019 08:29
Show Gist options
  • Save sizief/5dfa2c7ff15ec56a50817d067b8f83c7 to your computer and use it in GitHub Desktop.
Save sizief/5dfa2c7ff15ec56a50817d067b8f83c7 to your computer and use it in GitHub Desktop.
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