Returning all maximum or minimum values that can be multiple

后端 未结 3 694
情深已故
情深已故 2020-12-02 02:30

Enumerable#max_by and Enumerable#min_by return one of the relevant elements (presumably the first one) when there are multiple max

3条回答
  •  醉酒成梦
    2020-12-02 02:54

    This is the hash equivalent of @Serio's use of group_by.

    arr = [1, 2, 3, 5]
    
    arr.each_with_object(Hash.new { |h,k| h[k] = [] }) { |e,h| h[e%3] << e }.max.last
      #=> [2, 5]
    

    The steps:

    h = arr.each_with_object(Hash.new { |h,k| h[k] = [] }) { |e,h| h[e%3] << e }
      #=> {1=>[1], 2=>[2, 5], 0=>[3]}
    a = h.max
      #=> [2, [2, 5]]
    a.last
      #=> [2, 5]
    

提交回复
热议问题