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

Hi, I am trying to find the greatest value in my hash. I did a google search and I found this code:

def largest_hash_key(hash) key = hash.sort{|a,b| a[1] <=> b[1]}.last puts key end hash = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 } largest_hash_key(hash) 

in this "puts" code, the largest key and ex y300 value are output. So, how can I modify the code to find the largest value and put it in the to_s variable?

+3
source share
5 answers

This is O (n):

 h = {"n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0} key_with_max_value = h.max_by { |k, v| v }[0] #=> "y" 
+8
source

Here is another way to do what you want. This will find all 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"] 
+3
source

You can change your first method 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 a pair of key values ​​with the highest value. Its first element is the corresponding key.

+1
source

Sort the hash once, not search max. That way you can also get the smallest, etc.

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

The key is the highest value

 max = *h[0][0] 

Get Key / Lowest Value

 puts *h[h.length-1] 

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

0
source

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.

0
source

Source: https://habr.com/ru/post/916322/


All Articles