首页 > 解决方案 > Ruby sort_by 保持未排序的原始顺序

问题描述

我有一个看起来像这样的哈希:

{ "3g3dsd3" => {"price"=>0.12, "avg"=>81, "top"=>true}, "1sf3af" => {"price"=>0.14, "avg"=>121, "top"=>false}...}

我想对其重新排序,以便带有的项目"top"=>true位于顶部,但除此之外,这些项目将保持先前的顺序,这意味着具有相同top值的项目不会改变时间之间的顺序。

我在原始文档中找不到sort_by保持未排序属性顺序的证据。

我怎样才能做到这一点?

标签: ruby

解决方案


您可以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

推荐阅读