Skip to content

Instantly share code, notes, and snippets.

@ArnisL
Created October 10, 2016 20:33
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 ArnisL/33086aa40bcd99d5596a2b8e336a5ea9 to your computer and use it in GitHub Desktop.
Save ArnisL/33086aa40bcd99d5596a2b8e336a5ea9 to your computer and use it in GitHub Desktop.
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
@ArnisL
Copy link
Author

ArnisL commented Oct 10, 2016

mildly annoyed by repetition of 4th and 9th lines

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment