Created
December 14, 2016 03:11
-
-
Save dogenpunk/2e282e210e21f800c542f6776e96ab8f to your computer and use it in GitHub Desktop.
Ruby implementation of 'flatten'
This file contains hidden or 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
=begin rdoc | |
Takes any nested combination of Arrays and returns their contents as a | |
single Array. my_flatten(nil) returns an empty Array. | |
=end | |
def my_flatten values=[] | |
raise "`my_flatten' requires an Array argument." unless values.is_a?(Array) | |
result = [] | |
values.each do |v| | |
if v.is_a?(Array) | |
result.concat my_flatten(v) | |
else | |
result << v unless v.nil? | |
end | |
end | |
result | |
end | |
if __FILE__ == $0 | |
require 'minitest/autorun' | |
require 'minitest/pride' | |
class MyFlattenTest < MiniTest::Unit::TestCase | |
def test_flattens_to_arbitrary_depth | |
result = my_flatten([1, [2, 3], 4, [[5, 6, [7], 8], 9, 10], 11]) | |
assert_equal [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], result | |
end | |
def test_raises_exception_when_passed_non_array | |
assert_raises RuntimeError do | |
my_flatten(a: 1, b: [2]) | |
end | |
end | |
def test_eliminates_empty_arrays | |
result = my_flatten([1, [], 2, [3]]) | |
assert_equal [1, 2, 3], result | |
end | |
def test_eliminates_nils | |
result = my_flatten([1, nil, 3]) | |
assert_equal [1, 3], result | |
end | |
def returns_an_empty_array_when_called_with_no_argument | |
assert_equal [], my_flatten | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment