I think itβs nice to use something you find on Google and set it up until it somehow starts up. If we develop software, we must do what we understand.
A Hash is optimized for finding key values. It is not optimized to sort values ββor search by value properties. Thus, the data structure does not help your problem. Other data structures, such as trees or even arrays, might be better.
But if you want to use the hash due to some other reasons, of course, this is possible. Somehow you just need to iterate over the entire hash.
The algorithm is pretty simple: collapse the entire hash and check if the value is greater and the previous largest value:
max_value = 0 # or -Infinity if you have negative values key_for_max_value = nil hash.each_pair do | key, value | if value > max_value max_value = value key_for_max_value = key end end puts "The largest value is #{max_value} and it is has the key #{key_for_max_value}"
Some of the other solutions use tricks like sorting an array, but this only hides the complexity.
Meier source share