ruby - 如何对ruby中的嵌套哈希进行排序?
问题描述
example_hash = {
"1" => {"occurence": 12, "display": ""},
"2" => {"occurence": 15, "display": ""},
"3" => {"occurence": 16, "display": ""}
}
对于上面给出的嵌套哈希,我们如何根据出现值对其进行排序(降序)。结果应按排序顺序显示键 [3,2,1]
解决方案
example_hash.sort_by { |_,h| -h[:occurrence] }
#=> [["3", {:occurrence=>16, :display=>""}],
# ["2", {:occurrence=>15, :display=>""}],
# ["1", {:occurrence=>12, :display=>""}]]
如果需要散列,请继续.to_h
,但通常不希望散列具有以特定方式排序的键。
推荐阅读
- qt - Qt 小部件的 Width() 和 Height() API 的单位是什么?
- javascript - 如何在 Twig 语法中使用 post 方法
- php - session_destroy() 是否与登录失败尝试有关?
- linux - 在具有两个硬盘驱动器的双引导系统上克隆磁盘
- javascript - 在 vue 应用程序中显示 HTML 模板的实时预览
- magento - Magento 2.4 允许管理员从管理员订单中添加缺货产品
- c++ - 我如何在 esp2866 中输出 200khz
- powershell - 本地用户登录powershell
- spring-integration - 过滤从 http 出站网关获得 200 状态的消息
- c++ - 在 C++ 64 位环境下,是否存在 new 运算符的结果指针使用全部 8 个字节的情况?