我在数组nammed elem
中有哈希值,我必须得到具有最高“count”值的“type”键。
我知道普查员是一件很了不起的事情,但我对它们并不了解。
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
但我知道我错过了一些步骤。
我知道这种“机动”是相当普遍和重要的。
答案 0 :(得分:3)
执行此操作的一种方法是使用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