Skip to content

Instantly share code, notes, and snippets.

@agush22
Last active April 6, 2016 16:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agush22/14b65ee7724e2495b458 to your computer and use it in GitHub Desktop.
Save agush22/14b65ee7724e2495b458 to your computer and use it in GitHub Desktop.
Flatten arrays
require 'minitest/autorun'
require 'minitest/pride'
def flatten(array, res = [])
array.each do |el|
if el.kind_of? Array
flatten(el, res)
else
res << el
end
end
res
end
class FlattenTest < Minitest::Test
def test_no_nest
assert_equal [1,2,3,4,5,6], flatten([1,2,3,4,5,6])
end
def test_single
assert_equal [1,2,3,4,5,6], flatten([[1,2],3,4,[5,6]])
end
def test_double_nest
assert_equal [1,2,3,4,5,6], flatten([1,2,[3,4,[5,6]]])
end
def test_triple_nest
assert_equal [1,2,3,4,5,6], flatten([1,[2,[3,4,[5,6]]]])
end
def test_citrusbyte
assert_equal [1,2,3,4], flatten([[1,2,[3]],4])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment