10, "pears" => 15, "ba...">

Ruby: get hash pair with maximum value

Here's a hash that keeps track of how much each fruit I have

  fruits = {"apples" => 10, "pears" => 15, "bananas" => 15, "grapes" => 12}

And I want to know what fruits I have. If there are tiebreaks, then just return them all.

+6
source share
3 answers
# easy max_quantity = fruits.values.max max_fruits = fruits.select { |k, v| v == max_quantity }.keys # fast max_quantity = -1.0/0.0 max_fruits = [] fruits.each do |k, v| if v > max_quantity max_quantity = v max_fruits = [] end max_fruits.push k if v == max_quantity end 

Since the exceptional cases are Bad (tm), both of them always return an array.

+8
source
 max_value = fruits.values.max keys = fruits.select{|k, v| v == max_value}.keys 
+6
source

A shorter answer that uses Ruby Select to return the hash with the highest value (including tiebreakers)

 most_fruit = fruits.select {|x,i| i == fruits.values.max} 

Example:

 fruits = {"apples" => 10, "pears" => 15, "bananas" => 15, "grapes" => 12} fruits.select {|x,i| i == fruits.values.max } 

Exit

{"pears"=>15, "bananas"=>15}

0
source

Source: https://habr.com/ru/post/916318/


All Articles