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

前端 未结 5 1090
孤街浪徒
孤街浪徒 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 05:56

    You can modify your method's first statement to

    key = hash.sort{|a,b| a[1] <=> b[1]}.last[0]
    

    Hash.sort returns an array of key-value pairs. last gets you the key-value pair with the largest value. Its first element is the corresponding key.

提交回复
热议问题