How to find the key of the largest value hash? How to find the key of the largest value hash? ruby ruby

How to find the key of the largest value hash?


This will return max hash key-value pair depending on the value of hash elements:

def largest_hash_key(hash)  hash.max_by{|k,v| v}end


I found this way , return the key of the first max value

hash.key(hash.values.max)


Another way could be as follows:

hash.each { |k, v| puts k if v == hash.values.max }

This runs through each key-value pair and returns (or in this case puts's) the key(s) where the value is equal to the max of all values. This should return more than one key if there's a tie.