Skip to content

Instantly share code, notes, and snippets.

@goodviber
Last active February 24, 2020 19:40
Show Gist options
  • Select an option

  • Save goodviber/ec931d6eb262bd39cf5eead945ee1ccb to your computer and use it in GitHub Desktop.

Select an option

Save goodviber/ec931d6eb262bd39cf5eead945ee1ccb to your computer and use it in GitHub Desktop.

Revisions

  1. goodviber revised this gist Feb 24, 2020. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion array_flattener.rb
    Original file line number Diff line number Diff line change
    @@ -1,7 +1,8 @@
    class ArrayFlattener

    #recursive function
    def flatten_this(arr)
    raise ArgumentError, 'Argument is not an array' unless arr.is_a? Array
    raise ArgumentError, 'Argument is not an array' unless arr.is_a? Array
    arr.each_with_object([]) do | element, flat_array |
    flat_array.push *( element.is_a?(Array) ? flatten_this(element) : element )
    end
  2. goodviber created this gist Feb 24, 2020.
    10 changes: 10 additions & 0 deletions array_flattener.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    class ArrayFlattener

    def flatten_this(arr)
    raise ArgumentError, 'Argument is not an array' unless arr.is_a? Array
    arr.each_with_object([]) do | element, flat_array |
    flat_array.push *( element.is_a?(Array) ? flatten_this(element) : element )
    end
    end

    end
    31 changes: 31 additions & 0 deletions array_flattener_test.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    require 'minitest/autorun'
    require_relative 'array_flattener'

    class ArrayFlattenerTest < Minitest::Unit::TestCase

    def setup
    @array_flattener = ArrayFlattener.new
    end

    def test_with_empty_array
    assert_equal [], @array_flattener.flatten_this([[]])
    end

    def test_with_a_string
    assert_raises ArgumentError do
    @array_flattener.flatten_this("1,2,3,4")
    end
    end

    def test_with_nested_array
    assert_equal [1,2,3,4], @array_flattener.flatten_this([[1,2,[3]],4])
    end

    def test_with_flat_array
    assert_equal [1,2,3,4], @array_flattener.flatten_this([1,2,3,4])
    end

    def test_with_recurring_elements
    assert_equal [1,1,1,1,2,3,4], @array_flattener.flatten_this([[[1],[1]],1,[1],2,3,4])
    end
    end