How to find the key of the largest value hash?

RubyHash

Ruby Problem Overview


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"

Ruby Solutions


Solution 1 - Ruby

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 - Ruby

I found this way , return the key of the first max value

hash.key(hash.values.max)

Solution 3 - Ruby

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 - Ruby

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 - Ruby

You can use the select method if you want the key value pair returned:

hash.select {|k,v| v == hash.values.max }

Solution 6 - Ruby

I did this today on a similar problem and ended up with this:

hash = { "CA"=>2, "MI"=>1, "NY"=>1 }

hash.invert.max&.last
=> "CA" 

For Ruby less than 2.3 you can replace &.last with .try(:last) Either one is just a safeguard for if your source hash is empty: {}

Solution 7 - Ruby

This will return the last key of the hash sorted by size; however, there might be two keys with the same value.

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJZ.View Question on Stackoverflow
Solution 1 - RubyHckView Answer on Stackoverflow
Solution 2 - RubyTiberiu MacelaruView Answer on Stackoverflow
Solution 3 - RubyK. George PradhanView Answer on Stackoverflow
Solution 4 - RubyLinjuView Answer on Stackoverflow
Solution 5 - Rubyecoding5View Answer on Stackoverflow
Solution 6 - RubyJP DuffyView Answer on Stackoverflow
Solution 7 - RubythenengahView Answer on Stackoverflow