example_hash = {
"1" => {"occurence": 12, "display": ""},
"2" => {"occurence": 15, "display": ""},
"3" => {"occurence": 16, "display": ""}
}
对于上面给定的嵌套散列,我们如何根据出现值对其进行排序(降序)?结果应该以3,2,1的排序顺序显示键
发布于 2018-07-25 06:24:35
example_hash.sort_by { |_,h| -h[:occurrence] }
#=> [["3", {:occurrence=>16, :display=>""}],
# ["2", {:occurrence=>15, :display=>""}],
# ["1", {:occurrence=>12, :display=>""}]]
如果需要散列,则添加.to_h
,但通常不希望散列中的键以特定方式排序。
发布于 2018-07-25 05:10:40
在控制台中,如下所示:
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=>""}}
顺便说一句,我相信你把“occurence”拼错了。
https://stackoverflow.com/questions/51507439
复制相似问题