Created
October 10, 2016 20:33
-
-
Save ArnisL/33086aa40bcd99d5596a2b8e336a5ea9 to your computer and use it in GitHub Desktop.
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
def flatten integers | |
[].tap do |memory| | |
integers.each do |element| | |
memory << element if element.is_a? Fixnum | |
next unless element.is_a? Array | |
flatten(element).each do |element| | |
memory << element if element.is_a? Fixnum | |
end | |
end | |
end | |
end | |
require 'test/unit' | |
class Tests < Test::Unit::TestCase | |
def test_flatten | |
assert_equal [1], flatten([1]) | |
assert_equal [1, 2], flatten([1, 2]) | |
assert_equal [1], flatten([[1]]) | |
assert_equal [1, 2], flatten([[1], 2]) | |
assert_equal [1], flatten([[[1]]]) | |
assert_equal [1, 2], flatten([[[1], 2]]) | |
assert_equal [1, 2, 3, 4], flatten([[1, 2, [3]], 4]) | |
assert_equal [1, 2, 3, 4], flatten([[[1, 2, [3]]], 4]) | |
assert_equal [1, 2, 3, 4], flatten([nil, 1, [2, 3], [nil], 4]) | |
assert_equal [1, 2, 3, 4], flatten(['foo', 1, 2, 3, 3.5, 4]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
mildly annoyed by repetition of 4th and 9th lines