Search code examples
rubymultidimensional-arraynestedenumerable

Ruby Getting a max value out of a newly created array in one function


I want my function to return the longest Array within a nested array (including the array itself) so

nested_ary = [[1,2],[[1,2,[[1,2,3,4,[5],6,7,11]]]],[1,[2]]
deep_max(nested_ary)
 => [1,2,3,4,[5],6,7,11]

simple_ary = [1,2,3,4,5]
deep_max(simple_ary)
 => returns: [1,2,3,4,5]

I created a function to collect all arrays. I have to get the max value in another function.

my code:

def deep_max(ary)
  ary.inject([ary]) { |memo, elem|
  if elem.is_a?(Array)
    memo.concat(deep_max(elem))
  else
    memo
  end }
end

This gives me what I want:

deep_max(nested_ary).max_by{ |elem| elem.size }

Is there a way to get this max inside of the function?


Solution

  • def deep_max(arr)
      biggest_so_far = arr
      arr.each do |e|
        if e.is_a?(Array)
          candidate = deep_max(e)
          biggest_so_far = candidate if candidate.size > biggest_so_far.size
        end
      end
      biggest_so_far
    end
    
    deep_max [[1, 2], [[1, 2, [[1, 2, 3, 4, [5], 6, 7, 11]]]], [1, [2]]]
      #=> [1, 2, 3, 4, [5], 6, 7, 11]