Created
May 29, 2016 02:03
-
-
Save lihanli/6c16c34e74d80214498f7677ce4c0c42 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 'test/unit' | |
def flatten(array) | |
flattened_array = [] | |
array.each { |item| | |
if item.is_a?(Array) | |
flattened_array += flatten(item) | |
else | |
flattened_array << item | |
end | |
} | |
flattened_array | |
end | |
class FlattenTest < Test::Unit::TestCase | |
def test_flatten_basic_array | |
assert_equal([1, 2, 3], flatten([1, 2, 3])) | |
end | |
def test_flatten_one_inner_array | |
assert_equal([4, 5, 6, 7, 8], flatten([4, 5, 6, [7, 8]])) | |
end | |
def test_flatten_two_inner_arrays | |
assert_equal([1, 2, 3, 4, 5], flatten([1, 2, [3, [4, 5]]])) | |
end | |
def test_flatten_example_given | |
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