Ruby: get hash pair with maximum value
# 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.
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}