我在数组nammedelem
中有散列,我必须得到“type”键,它具有最高的“count”值。
我知道枚举数是一件很好的事情,但我不太了解他们。
elem = [{"type"=>"dododo", "count"=>0, "name"=>"dododo's", "tip"=>"dododo's Level"},
{"type"=>"dadada", "count"=>1203, "name"=>"dadada's", "tip"=>"dadada's Degree"},
{"type"=>"dedede", "count"=>717, "name"=>"dedede's", "tip"=>"dedede's Degree"},
{"type"=>"dididi", "count"=>6, "name"=>"dididi's", "tip"=>"dididi or Professional Degree"}]
我在尝试:
elem.each do |i|
i.each_with_index do |k,v|
puts v["count"]
end
end
但我知道我漏了一步。
我知道,这种“策略”是相当常见和重要的知道。
最佳答案
一种方法是使用Enumerable#max_by
elem = [
{"type"=>"dododo", "count"=>0, "name"=>"dododo's", "tip"=>"dododo's Level"},
{"type"=>"dadada", "count"=>1203, "name"=>"dadada's", "tip"=>"dadada's Degree"},
{"type"=>"dedede", "count"=>717, "name"=>"dedede's", "tip"=>"dedede's Degree"},
{"type"=>"dididi", "count"=>6, "name"=>"dididi's", "tip"=>"dididi or Professional Degree"}
]
max_elem = elem.max_by {|e| e['count']}
puts max_elem['type']
# returns dadada
关于ruby - 如何对具有最高特定值的哈希排序?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24440415/