Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning all maximum or minimum values that can be multiple

Tags:

ruby

max

min

maxby

Enumerable#max_by and Enumerable#min_by return one of the relevant elements (presumably the first one) when there are multiple max/min elements in the receiver. For example, the following:

[1, 2, 3, 5].max_by{|e| e % 3}

returns only 2 (or only 5).

Instead, I want to return all max/min elements and in an array. In the example above, it would be [2, 5] (or [5, 2]). What is the best way to get this?

like image 673
sawa Avatar asked Mar 01 '14 15:03

sawa


1 Answers

arr = [1, 2, 3, 5]

arr.group_by{|a| a % 3} # => {1=>[1], 2=>[2, 5], 0=>[3]}
arr.group_by{|a| a % 3}.max.last # => [2, 5]
like image 112
Sergio Tulentsev Avatar answered Sep 18 '22 18:09

Sergio Tulentsev