如何对哈希的散列进行排序

时间:2012-09-06 19:33:24

标签: ruby hash

我正在努力对下面列出的哈希进行排序:

{
  17=>{:id=>17, :count=>1, :created_at=>Wed, 05 Sep 2012 19:02:34 UTC +00:00},
  14=>{:id=>14, :count=>2, :created_at=>Sun, 02 Sep 2012 19:20:28 UTC +00:00},
  9=>{:id=>9, :count=>0, :created_at=>Sun, 02 Sep 2012 17:09:35 UTC +00:00},
  10=>{:id=>10, :count=>2, :created_at=>Sat, 01 Sep 2012 17:09:56 UTC +00:00},
  11=>{:id=>11, :count=>0, :created_at=>Fri, 31 Aug 2012 19:13:57 UTC +00:00},
  12=>{:id=>12, :count=>2, :created_at=>Thu, 30 Aug 2012 19:19:32 UTC +00:00},
  13=>{:id=>13, :count=>0, :created_at=>Thu, 23 Aug 2012 19:20:09 UTC +00:00}
}

上面的哈希应该在countcreated_of上排序,看起来像这个哈希:

{
  12=>{:id=>12, :count=>2, :created_at=>Thu, 30 Aug 2012 19:19:32 UTC +00:00},
  10=>{:id=>10, :count=>2, :created_at=>Sat, 01 Sep 2012 17:09:56 UTC +00:00},
  14=>{:id=>14, :count=>2, :created_at=>Sun, 02 Sep 2012 19:20:28 UTC +00:00},
  17=>{:id=>17, :count=>1, :created_at=>Wed, 05 Sep 2012 19:02:34 UTC +00:00},
  13=>{:id=>13, :count=>0, :created_at=>Thu, 23 Aug 2012 19:20:09 UTC +00:00},
  11=>{:id=>11, :count=>0, :created_at=>Fri, 31 Aug 2012 19:13:57 UTC +00:00},
  9=>{:id=>9, :count=>0, :created_at=>Sun, 02 Sep 2012 17:09:35 UTC +00:00}
}

2 个答案:

答案 0 :(得分:3)

假设您正在使用Ruby 1.9,其中哈希具有顺序:

Hash[data.sort_by { |key, h| [-h[:count], h[:created_at]] }]

答案 1 :(得分:2)

在Ruby 1.8中,您无法对哈希进行排序,因为哈希没有顺序。在Ruby 1.9中,哈希迭代顺序由插入顺序定义。因此,您必须创建一个新哈希,您将在其中以正确的顺序插入元素。

sorted_keys = hash.keys.sort
sorted_hash = Hash.new
sorted_keys.each do |k|
  sorted_hash[k] = hash[k]
end