Created
February 22, 2018 17:02
-
-
Save bbuchalter/811778460f94c7ffae9c194c6dff286c 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 'minitest/autorun' | |
class TestMyFlatten < Minitest::Test | |
def test_deeply_nested_arrays | |
assert_equal [1,2,3,4], MyFlatten.new([[1,2,[3]],4]).flatten | |
end | |
def test_argument_error | |
assert_raises ArgumentError do | |
MyFlatten.new("not an array") | |
end | |
end | |
end | |
class MyFlatten | |
def initialize(original) | |
raise ArgumentError unless original.is_a?(Array) | |
@original = original | |
end | |
def flatten | |
flattened = [] | |
original.each do |element| | |
if element.is_a?(Array) | |
flattened += self.class.new(element).flatten | |
else | |
flattened << element | |
end | |
end | |
flattened | |
end | |
private | |
attr_reader :original | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment