Skip to content

Instantly share code, notes, and snippets.

@apbarrero
Created March 13, 2016 21:45
Show Gist options
  • Save apbarrero/6c5a5f14451a6e1caad1 to your computer and use it in GitHub Desktop.
Save apbarrero/6c5a5f14451a6e1caad1 to your computer and use it in GitHub Desktop.
Array flatten
#!/usr/bin/env ruby
require 'test/unit'
def flatten(array)
f = []
if array.kind_of?(Array)
array.each{ |e| f.concat(e.kind_of?(Array) ? flatten(e) : [e]) }
else
f = [array]
end
f
end
class TestFlatten < Test::Unit::TestCase
def test_empty
assert_equal([], flatten([]))
end
def test_already_flatten
assert_equal([1,2,3], flatten([1,2,3]))
end
def test_one_nested_array
assert_equal([1,2,3], flatten([1,[2,3]]))
end
def test_two_nesting_levels
assert_equal([1,2,3,4], flatten([[1,2,[3]],4]))
end
def test_not_array_input_returns_one_element_array
assert_equal([1], flatten(1))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment