这是一个哈希,记录我有多少水果
fruits = {"apples" => 10,"pears" => 15,"bananas" => 15,"grapes" => 12}
而且我想知道我最常吃的是哪种水果.
如果有断路器,那么就把它们全部归还.
解决方法
# 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
由于异常情况为Bad(tm),因此这两种情况总是返回一个数组.