Ruby - find the key of the highest hash value (s)

I have a hash, and I want to return the key (or key / value pair) of the maximum hash value (s). So, if there is only one true max, it will return that one key; however, if there are several key / value pairs with the same value, it will return all of these keys. How can I accomplish this in Ruby?

my_hash.max_by {|k,v| v} #only returns one key/value pair 
+6
source share
2 answers

If you want all pairs, I would do something like

 max = my_hash.values.max Hash[my_hash.select { |k, v| v == max}] 
+11
source

One liner:

 my_hash.reduce({}){|h,(k,v)| (h[v] ||= []) << k;h}.max irb > z = {:tree => 3, :two => 2, 'three' => 3} > z.reduce({}){|h,(k,v)| (h[v] ||= []) << k;h}.max [3, [:tree, "three"]] 
+2
source

All Articles