In Ruby, if you want to get the key(s) of the largest value in a hash map, including any possible duplicates, you can do either the following:
Please note that these methods will return the key of the largest value as well as any duplicates of it. If you want to just return the first match instead, then you can use alternative approaches.
Using Enumerable#select
With Enumerable#select
, you can follow these steps to get key(s) of the largest value in a hash map, including duplicates:
- Use the
Enumerable#select
(orEnumerable#filter
) method to remove values from the hash that don't match the largest value; - Return an array of keys from the filtered hash using the
Hash#keys
method.
For example, you can implement this using the Enumerable#select
method in the following way:
def max_value_keys(hash) max_value = hash.values.max max_values = hash.select { | key, value | value == max_value } max_values.keys end print max_value_keys({ a: 20, b: 50, c: 30 }) #=> [:b] print max_value_keys({ a: 20, b: 50, c: 50 }) #=> [:b, :c] print max_value_keys({ a: -20, b: -50, c: -30 }) #=> [:a] print max_value_keys({}) #=> []
This method involves multiple iterations over the hash map, returning an array of keys corresponding to the matching values. If an empty hash is provided as input, the method will return an empty array.
You may substitute Enumerable#select
with Enumerable#filter
as they are aliases of each other, and can be used interchangeably.
Using Hash#each
You can use the Hash#each
method to iterate over each item in the hash map, and determine the key(s) of the largest value:
def max_value_keys(hash) max_value = nil keys = [] hash.each do | key, value | if max_value.nil? || value > max_value max_value = value keys = [key] elsif value == max_value keys << key end end keys end print max_value_keys({ a: 20, b: 50, c: 30 }) #=> [:b] print max_value_keys({ a: 20, b: 50, c: 50 }) #=> [:b, :c] print max_value_keys({ a: -20, b: -50, c: -30 }) #=> [:a] print max_value_keys({}) #=> []
This approach iterates over the hash map only once, keeping track of the maximum value encountered so far and accumulating keys that have the same maximum value. if an empty hash is provided as input, the method will return an empty array.
This post was published (and was last revised ) 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.