Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: get hash pair with max value

Tags:

ruby

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

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

And I want to know which fruit I have the most of.
If there are tie-breakers then just return them all.

like image 713
MxLDevs Avatar asked May 22 '12 03:05

MxLDevs


2 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 exceptional cases are Bad(tm), both of these always return an array.

like image 115
Amadan Avatar answered Oct 18 '22 10:10

Amadan


max_value = fruits.values.max
keys = fruits.select{|k, v| v == max_value}.keys
like image 29
xdazz Avatar answered Oct 18 '22 09:10

xdazz