如何按值对哈希进行排序 [英] How to sort a hash by values

查看:69
本文介绍了如何按值对哈希进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图按值对特定散列进行排序.我遇到了一种使用 sort_by 方法的方法.但即使我在散列上调用 sort_by,它也会返回一个数组,即:

I was trying to sort a particular hash by values. I came across a way using the method sort_by. But even though I call sort_by on a hash, it returns an array, i.e.:

a = {}
a[0] = "c"
a[1] = "b"
a[2] = "a"
a.sort_by{|key, value| value}
# => [[2, "a"], [1, "b"], [0, "c"]]

如果我尝试将结果转换为散列,我最终会得到一个按键排序的散列,因此 sort_by 的全部目的就失去了.即:

If I try to convert the result into a hash, I end up with a hash sorted on key, hence the whole purpose of sort_by is lost. i.e.:

a = {}
a[0] = "c"
a[1] = "b"
a[2] = "a"
Hash[*a.sort_by{|key, value| value}.flatten]
# => {0=>"c", 1=>"b", 2=>"a"}

有没有一种方法可以按值对散列进行排序,然后以散列的形式返回结果?

Is there a way I can sort a hash by value and yet get the results back in the form of a Hash?

我使用的是 1.8.6 ruby​​

I am using 1.8.6 ruby

推荐答案

您可以使用 <代码>ActiveSupport::OrderedHash 用于 Ruby 1.8:

You can use ActiveSupport::OrderedHash for Ruby 1.8:

ActiveSupport::OrderedHash 实现了一个保持插入顺序的哈希,就像在 Ruby 1.9 中一样

ActiveSupport::OrderedHash implements a hash that preserves insertion order, as in Ruby 1.9

我没有运行 1.8.6,但这应该可以工作:

I don't have 1.8.6 running, but this should work:

a = {}
a[0] = "c"
a[1] = "b"
a[2] = "a"

ordered = ActiveSupport::OrderedHash[*a.sort_by{|k,v| v}.flatten]
ordered.keys
# => [2, 1, 0], this order is guaranteed

正如上面引用的 Ruby 1.9 中的散列 按照插入相应键的顺序枚举它们的值",因此只有 Ruby 1.8 需要这样做.

As noted in the quote above hashes in Ruby 1.9 "enumerate their values in the order that the corresponding keys were inserted", so this is only needed for Ruby 1.8.

这篇关于如何按值对哈希进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆