Skip to content

Instantly share code, notes, and snippets.

@dogenpunk
Created December 14, 2016 03:11
Show Gist options
  • Select an option

  • Save dogenpunk/2e282e210e21f800c542f6776e96ab8f to your computer and use it in GitHub Desktop.

Select an option

Save dogenpunk/2e282e210e21f800c542f6776e96ab8f to your computer and use it in GitHub Desktop.

Revisions

  1. dogenpunk created this gist Dec 14, 2016.
    54 changes: 54 additions & 0 deletions flatten.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,54 @@
    =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