如何在ruby中对嵌套哈希进行排序?

时间:2018-07-24 20:58:54

标签: ruby hash

example_hash = {
  "1" => {"occurence": 12, "display": ""},
  "2" => {"occurence": 15, "display": ""},
  "3" => {"occurence": 16, "display": ""}
}

对于上面给定的嵌套哈希,我们如何根据出现值对它进行排序(降序)。结果应按[3,2,1]

的顺序显示键

2 个答案:

答案 0 :(得分:3)

example_hash.sort_by { |_,h| -h[:occurrence] }
  #=> [["3", {:occurrence=>16, :display=>""}],
  #    ["2", {:occurrence=>15, :display=>""}],
  #    ["1", {:occurrence=>12, :display=>""}]]

如果需要散列,请.to_h进行修改,但通常不希望使用以特定方式排序的键来进行散列。

答案 1 :(得分:1)

在控制台中,这是

example_hash.sort{|a,b| b[1][:occurence] <=> a[1][:occurence]}.to_h

返回此:

{"3"=>{:occurence=>16, :display=>""}, "2"=>{:occurence=>15, :display=>""}, "1"=>{:occurence=>12, :display=>""}}

顺便说一句,我相信您拼错了“出现率”。