How to find the key of the largest value hash?
Solution 1
This will return max hash key-value pair depending on the value of hash elements:
def largest_hash_key(hash)
hash.max_by{|k,v| v}
end
Solution 2
I found this way , return the key of the first max value
hash.key(hash.values.max)
Solution 3
Another way could be as follows:
hash.each { |k, v| puts k if v == hash.values.max }
This runs through each key-value pair and returns (or in this case puts's) the key(s) where the value is equal to the max of all values. This should return more than one key if there's a tie.
Solution 4
If you want to retrieve more than one key value pair based on order(second largest, smallest etc.), a more efficient way will be to sort the hash once and then get the desired results.
def descend_sort(hash)
hash = hash.sort_by {|k,v| v}.reverse
end
Key of largest value
puts *hash[0][0]
Get max and min
puts *hash[0], *hash[hash.length-1]
2nd largest key value pair
Hash[*hash[1]]
To convert the hash array back into a hash
hash.to_h
Solution 5
You can use the select method if you want the key value pair returned:
hash.select {|k,v| v == hash.values.max }
Comments
-
JZ. over 4 years
I have the following hash
{"CA"=>2, "MI"=>1, "NY"=>1}
How can I return the maximum key value pair using ruby? I would like it to return "CA"
-
tokland about 13 yearsselected answer? may_by is much better than a low-level sort. It's more compact and uses less memory than a sort+last.
-
justingordon about 10 yearsworth noting you get back a 2 element array with [key, value]
-
nfriend21 over 9 yearshash.max_by{ |k,v| v }[0] gives the key.
-
Robbie Guilfoyle about 9 yearsAlso worth noting a tie will go to first in order of position.
-
mahemoff almost 9 yearsYou can also do hash.max_by(&:last) for the pair and hash.max_by(&:last).first for the key.
-
Scott Jodoin almost 3 yearsBe warned that this does not work if the hash is empty.
-
Schwern over 2 yearsWhile
hash[key]
is very efficient,hash.key(value)
has to search the whole hash. This answer searches the hash twice: first to find the maximum value, then to find the key which matches that value.