首页 > 解决方案 > 如何对ruby中的嵌套哈希进行排序?

问题描述

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

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

标签: rubyhash

解决方案


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

如果需要散列,请继续.to_h,但通常不希望散列具有以特定方式排序的键。


推荐阅读