Skip to content

Instantly share code, notes, and snippets.

@aybarshazar
Last active March 18, 2017 10:10
Show Gist options
  • Select an option

  • Save aybarshazar/d55a1fedf8c6fc4c6c074ec1ae56bee0 to your computer and use it in GitHub Desktop.

Select an option

Save aybarshazar/d55a1fedf8c6fc4c6c074ec1ae56bee0 to your computer and use it in GitHub Desktop.

Revisions

  1. aybarshazar revised this gist Mar 18, 2017. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion flatten.rb
    Original file line number Diff line number Diff line change
    @@ -15,4 +15,4 @@ def flatten(arr)

    flatten([1, 2, 3, 4, 5, 6, 7, 8]) == [1, 2, 3, 4, 5, 6, 7, 8]
    flatten([1, 2, [3, [4, 5, 6], 7], 8]) == [1, 2, 3, 4, 5, 6, 7, 8]
    flatten([[1, [11], [25, 33, [43, 39], [15], 21], 18], 2, [3, [4, 5, 6], 7], 8]) == [1, 11, 25, 33, 43, 39, 15, 21, 18, 2, 3, 4, 5, 6, 7, 8]
    flatten([[1, 11], 2, [25, 33, [43, 39], [15], 21], 18]) == [1, 11, 2, 25, 33, 43, 39, 15, 21, 18]
  2. aybarshazar created this gist Mar 18, 2017.
    18 changes: 18 additions & 0 deletions flatten.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    def flatten(arr)
    result = []

    arr.each do |item|
    if item.is_a?(Array)
    sub_array = flatten(item)
    sub_array.each { |sub_item| result << sub_item }
    else
    result << item
    end
    end

    result
    end

    flatten([1, 2, 3, 4, 5, 6, 7, 8]) == [1, 2, 3, 4, 5, 6, 7, 8]
    flatten([1, 2, [3, [4, 5, 6], 7], 8]) == [1, 2, 3, 4, 5, 6, 7, 8]
    flatten([[1, [11], [25, 33, [43, 39], [15], 21], 18], 2, [3, [4, 5, 6], 7], 8]) == [1, 11, 25, 33, 43, 39, 15, 21, 18, 2, 3, 4, 5, 6, 7, 8]