@participants[id] = {nick: nick, points: 1}
=> {"1"=>{:nick=>"Test", :points=>3}, "30"=>{:nick=>"AnotherTest", :points=>5}, "20"=>{:nick=>"Newtest", :points=>3}}
我希望得到最低分(ID: 1 and 20)
。我如何获得最低分,然后ID 30最后?
答案 0 :(得分:2)
哈希不适合此操作的数据结构。它们意味着您需要获得O(1)
复杂度的值。
如果您对比较感兴趣或者Heap(如果您只对最大值或最小值感兴趣),最好使用排序数组或树,如@Vadim建议
答案 1 :(得分:2)
如果您使用Enumerable#max_by()或Enumerable#min_by(),则可以执行以下操作;
data = {
"1" => {nick: "U1", points: 3},
"30" => {nick: "U30", points: 5},
"20" => {nick: "U20", points: 3}
}
max_id, max_data = data.max_by {|k,v| v[:points]}
puts max_id # => 30
puts max_data # => {nick: "U30", points: 5}
同样的事情适用于#min_by(),如果你想回来Hash,你可以这样做:
minimal = Hash[*data.min_by {|k,v| v[:points]}]
puts minimal # => {"1"=>{:nick=>"U1", :points=>3}}
函数min_by()和max_by()将始终返回一条记录。如果你想获得具有相同点数的所有记录,那么你必须使用最小/最大数据来做另一个"查找"像这样:
min_id, min_data = data.min_by {|k,v| v[:points]}
all_minimal = data.select {|k,v| v[:points] == min_data[:points]}
puts all_minimal
# => {"1"=>{:nick=>"U1", :points=>3}, "20"=>{:nick=>"U20", :points=>3}}
答案 2 :(得分:0)
h = { "1"=>{:nick=>"Test", :points=>3},
"30"=>{:nick=>"AnotherTest", :points=>5},
"20"=>{:nick=>"Newtest", :points=>3}}
h.minmax_by { |_,g| g[:points] }
#=> [[ "1", {:nick=>"Test", :points=>3}],
# ["30", {:nick=>"AnotherTest", :points=>5}]]
答案 3 :(得分:0)
您可以通过合并min_by
和max_by
来解决sort
和chunk
只返回一个结果的事实:
data.sort_by{|_,v| v[:points]}.chunk{|(_,v)| v[:points]}.first.last.map(&:first)
#=> ["1", "20"]