Ruby: How to find the key of the largest value in a hash?

前端 未结 5 1095
孤街浪徒
孤街浪徒 2020-12-17 05:18

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|          


        
5条回答
  •  一生所求
    2020-12-17 06:13

    Here is another way of doing what you want. This will find all the keys with the maximum value:

    h = {"n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0, "z" => 300}          
    max = h.values.max
    output_hash = Hash[h.select { |k, v| v == max}]
    puts "key(s) for the largest value: #{output_hash.keys}"
    
    #=>key(s) for the largest value: ["y", "z"]
    

提交回复
热议问题