You can get the key of the largest numeric value in a Ruby hash map in the following ways:
Please note that these methods will return only the first match in case of duplicates of the maximum value. However, you can use alternative approaches if you want to have an array of all matches returned instead.
Using Enumerable#max_by
You can do the following:
- Iterate over the key-value pairs of the hash map using
Enumerable#max_by
; - Specify the value in the block to identify the pair with the maximum value, and return it as an array;
- Call the
Enumerable#first
method with the safe navigation operator (&.
) to safely return the key (which would be the first element of the resulting array).
For example, you can implement this in the following way:
def max_value_key(hash) max_hash = hash.max_by { | key, value | value } max_hash&.first end print max_value_key({ a: 20, b: 50, c: 30 }) #=> b print max_value_key({ a: 20, b: 50, c: 50 }) #=> b print max_value_key({ a: -20, b: -50, c: -30 }) #=> a print max_value_key({}) #=> nil
You may shorten this to the following one-liner:
def max_value_key(hash) hash.max_by(&:last)&.first end print max_value_key({ a: 20, b: 50, c: 30 }) #=> b print max_value_key({ a: 20, b: 50, c: 50 }) #=> b print max_value_key({ a: -20, b: -50, c: -30 }) #=> a print max_value_key({}) #=> nil
In this shorthand, the &:last
symbol simply returns the value
from the key-value pair passed to the block.
Using Hash#each
You can do the following:
- Iterate over the key-value pairs of the hash map using
Hash#each
; - Compare value of each item to find the largest value and its corresponding key;
- When the iteration finishes, return the key for the largest value.
def max_value_key(hash) max_key = nil max_value = nil hash.each do | key, value | if max_value.nil? || value > max_value max_key = key max_value = value end end max_key end print max_value_key({ a: 20, b: 50, c: 30 }) #=> b print max_value_key({ a: 20, b: 50, c: 50 }) #=> b print max_value_key({ a: -20, b: -50, c: -30 }) #=> a print max_value_key({}) #=> nil
Using Enumerable#max
You can do the following:
- Return an array of all the values using
Hash#values
; - Find the maximum value using
Enumerable#max
; - Use the
Hash#key
method to locate the corresponding key.
For example, you can implement this in the following way:
def max_value_key(hash) hash.key(hash.values.max) end print max_value_key({ a: 20, b: 50, c: 30 }) #=> b print max_value_key({ a: 20, b: 50, c: 50 }) #=> b print max_value_key({ a: -20, b: -50, c: -30 }) #=> a print max_value_key({}) #=> nil
It's worth mentioning that this method involves multiple iterations/passes through the enumerable.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.