ruby - Ruby sort_by 保持未排序的原始顺序
问题描述
我有一个看起来像这样的哈希:
{ "3g3dsd3" => {"price"=>0.12, "avg"=>81, "top"=>true}, "1sf3af" => {"price"=>0.14, "avg"=>121, "top"=>false}...}
我想对其重新排序,以便带有的项目"top"=>true
位于顶部,但除此之外,这些项目将保持先前的顺序,这意味着具有相同top
值的项目不会改变时间之间的顺序。
我在原始文档中找不到sort_by
保持未排序属性顺序的证据。
我怎样才能做到这一点?
解决方案
您可以sort_by
通过合并with_index
.
代替:
collection.sort_by { |...| ... }
你写:
collection.sort_by.with_index { |(...), i| [..., i] }
适用于您的问题:
hash.sort_by { |_k, v| v['top'] ? 0 : 1 } # unstable
hash.sort_by.with_index { |(_k, v), i| [v['top'] ? 0 : 1, i] } # stable
推荐阅读
- dc.js - 在 numberDisplay dc.js 中显示维度的最大值
- python - PYODBC/SQL:协助包含多个 SQL 语句的字符串
- python - 条件不满足时,Flask Restplus 禁用 API Endpoint
- angularjs - 角度模型刷新后如何在ng-repeat指令中设置元素位置的顶部和左侧
- php - php中未定义的变量,怎么了?
- ruby - Capybara / Ruby - 试图返回所有标签和 html 属性
- swift - 如何在firebase swift 4中使用childByAutoId获取自动生成的数字
- python - 根据列表中的名称创建列表
- linux - 使用不支持 %e 的 udev 规则枚举符号链接
- php - 如何使用 array_merge