Ruby - 找到散列最大值的关键字 [英] Ruby - find the key(s) of the largest value(s) of a hash

查看:80
本文介绍了Ruby - 找到散列最大值的关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个散列,我想返回散列最大值的键(或键/值对)。所以,如果只有一个真正的最大值,它将返回一个密钥;但是,如果有多个具有相同值的键/值对,它将返回所有这些键。如何在Ruby中完成这项工作?

I have a hash and I want to return the key(s) (or key/value pair(s)) of the max value(s) of the hash. So, if there is only one true max, it will return that one key; however, if there are multiple key/value pairs with the same value, it will return all of these keys. How can I accomplish this in Ruby?

my_hash.max_by {|k,v| v} #only returns one key/value pair


推荐答案

你想要所有的对,我会做一些像

If you want all pairs, I would do something like

max = my_hash.values.max
Hash[my_hash.select { |k, v| v == max}]

这篇关于Ruby - 找到散列最大值的关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆