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.
# 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.
max_value = fruits.values.max
keys = fruits.select{|k, v| v == max_value}.keys
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With