Search code examples
arraysrubysortingmonkeypatchingmaxima

How to implement Ruby max_by to return all elements which have the maximum value?


Ruby max_by method finds the maximal element form an array. Sometimes the maximal elements are with multipicity, in this case max_by chooses only one of them, seemingly arbitrarily. When I need all of them, I use this approach currently, to find the maximal values in an array of arrays:

sorted=ary.sort_by{|a,b| b}.reverse
max_score=sorted.first[1]
t=sorted.take_while{|z| z[1]==max_score}

But how could I monkey-patch the Array class with a "maxes_by" method, which accept a block, similarly to max_by, and returns an array of the maximal values?


Solution

  • Without writing a new, optimized method that returns the expected output, you can combine max_by and select:

    maximum = array.max_by { |element| element[1] }
    t = array.select { |element| element[1] == maximum[1] }
    

    Another option might be to group all elements by the value in question (with group_by) and then just pick the list with the max value.

    lists = array.group_by { |element| element[1] }
    lists[lists.keys.maximum]