Ruby哈希:返回具有最高值的键

时间:2014-04-02 17:25:45

标签: ruby hash maxby

我想根据最大键值返回一个哈希键/值对。我知道max_by有效,但它会在第一个结果处停止。如果出现平局,我怎样才能返回所有结果?

{
  foo: 1,
  bar: 3,
  baz: 3
}.max_by { |key, value| value }

#=> [:bar 3] # Only bar comes back, but baz also has a value of 3.

1 个答案:

答案 0 :(得分:1)

我会这样做:

hash = {
         foo: 1,
         bar: 3,
         baz: 3
       }

hash.group_by { |_,value| value }.max_by { |key,_| key }.last
# => [[:bar, 3], [:baz, 3]]

打破上述代码:

hash.group_by { |_,v| v } 
# => {1=>[[:foo, 1]], 3=>[[:bar, 3], [:baz, 3]]}
hash.group_by { |_,v| v }.max_by { |k,_| k }
# => [3, [[:bar, 3], [:baz, 3]]]