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

前端 未结 5 1103
孤街浪徒
孤街浪徒 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:55

    Sort the hash once instead of finding max. This way you can also get smallest etc.

    def reverse_sort_hash_value(hash)
       hash = hash.sort_by {|k,v| v}.reverse
    end
    
    h = reverse_sort_hash_value(h)
    

    Key of largest value

    max = *h[0][0]
    

    Get Key/Value of the smallest value

    puts *h[h.length-1]
    

    You can convert to hash using Hash[h.select { |k, v| v == max}] or using h.to_h

提交回复
热议问题