7

I have a hash and I want to return the key(s) (or key/value pair(s)) of the max value(s) of the hash. So, if there is only one true max, it will return that one key; however, if there are multiple 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
diasks2
  • 2,033
  • 2
  • 36
  • 61

2 Answers2

11

If you want all pairs, I would do something like

max = my_hash.values.max
Hash[my_hash.select { |k, v| v == max}]
oldergod
  • 15,033
  • 7
  • 62
  • 88
2

A single 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"]]
ShadyKiller
  • 700
  • 8
  • 16