I am trying to independently implement the work of the flatten method. It turned out to perform the implementation in which all the nested arrays are removed.

a = [ 1, 2, [3, [4, 5] ] ] def my_flatten(arr) arr.reduce([]) do |result, item| item.is_a?(Array) ? result + my_flatten(item) : result << item end end my_flatten(a) #=> [1, 2, 3, 4, 5] 

It is impossible to implement an algorithm in which you can specify the level for recursion. Example of the original method:

 a = [ 1, 2, [3, [4, 5] ] ] a.flatten(1) #=> [1, 2, 3, [4, 5]] 

    1 answer 1

     def my_flatten(arr, max_depth = nil, current_depth = 0) arr.reduce([]) do |result, item| if item.is_a?(Array) && (max_depth.nil? || current_depth < max_depth) result + my_flatten(item, max_depth, current_depth + 1) else result << item end end end