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"