Ruby:如何在哈希中找到最大值的键? [英] Ruby: How to find the key of the largest value in a hash?
本文介绍了Ruby:如何在哈希中找到最大值的键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,我正在尝试在哈希中找到最大值. 我在Google上进行了搜索,发现了以下代码:
Hello I'm trying to find the largest value in my hash. I made a search in google and I found this code:
def largest_hash_key(hash)
key = hash.sort{|a,b| a[1] <=> b[1]}.last
puts key
end
hash = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 }
largest_hash_key(hash)
在此代码中的
"puts"打印最大的键和值e.x y300. 那么,如何修改代码以找到最大值并将其关键字放入to_s变量中?
in this code "puts" prints the largest key and value e.x y300. So, how I can modify the code in order to find the largest value and put it's key in to_s variable?
推荐答案
这是O(n):
h = {"n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0}
key_with_max_value = h.max_by { |k, v| v }[0] #=> "y"
这篇关于Ruby:如何在哈希中找到最大值的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文