Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - find the key(s) of the largest value(s) of a hash

Tags:

ruby

hash

max

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
like image 656
diasks2 Avatar asked Oct 22 '12 05:10

diasks2


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}]
like image 98
oldergod Avatar answered Sep 28 '22 16:09

oldergod


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"]]
like image 25
ShadyKiller Avatar answered Sep 28 '22 16:09

ShadyKiller