Ruby: How to Find the Key of the Largest Value in a Hash

How to find the key of the largest value hash?

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

How do I get the maximum value of a hash in Ruby?

I would use the max method on the values of the hash:

{a: 1, b: 2}.values.max

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

If you want all pairs, I would do something like

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

Finding the largest value in a nested hash

game_hash[:home][:players].max_by { |_name, stats| stats[:shoe] }.last[:shoe]
#=> 19

How to find the max value in an array of hashes?

You can do this with group_by and max:

arr.group_by { |x| x[:total] }.max.last

Find maximum value of values in hash where key value in array

A simple way is this:

AvailableDomains.map { |k| object[k.to_sym] }.max

Here's another way to do it:

object.with_indifferent_access.values_at(*AvailableDomains).max

If the array contained symbols, the with_indifferent_access would be unnecessary, but it's used here so that the Array's strings can match the hash's symbol keys.

Find the highest value in an array of hashes in Ruby

You can use max_bymethod

students = [ { name: "Mary Jones", test_score: 80, sport: "soccer" }, { name: "Bob Kelly", test_score: 95, sport: "basketball" }, { name: "Kate Saunders", test_score: 99, sport: "hockey" }, { name: "Pete Dunst", test_score: 88, sport: "football" } ]

students.max_by{|k| k[:test_score] }
#=> {:name=>"Kate Saunders", :test_score=>99, :sport=>"hockey"}

students.max_by{|k| k[:test_score] }[:name]
#=> "Kate Saunders"

getting the largest value from a hash that is the value of another hash?

hash = {:foo =>{"string0"=>1, "string1"=>2}, :bar => {"string0"=>3, "string1"=>4}}
Hash[*hash.max_by { |_k, v| v['string0'] }]
#=> {:bar=>{"string0"=>3, "string1"=>4}}

To get the actual value:

hash.map { |_k, v| v['string0'] }.max
#=> 3


Related Topics



Leave a reply



Submit