giovannibenussi
9/22/2016 - 6:03 PM

array_flatten.rb

class Array
    # Returns the flatten version of the array
    # example: [[1,2,[3]],4] -> [1, 2, 3, 4]
    def flatten
        out = []
        self.each do | e |
            if e.is_a? Array
                out += e.flatten
            else
                out.push(e)
            end
        end
        return out
    end
end

test_arrays = [
    [[1,2,[3]],4],
    [[1,[2,3,[[4]]]]],
    []
]

for test_array in test_arrays
    puts "#{test_array} -> #{test_array.flatten.to_s}"
end
# Output:
# [[1, 2, [3]], 4] -> [1, 2, 3, 4]
# [[1, [2, 3, [[4]]]]] -> [1, 2, 3, 4]
# [] -> []