Kashiftufail
Kashiftufail

Reputation: 10885

How sort this hash of hashes

I am struggling to sort this hash listed below:

{
  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}
}

The above hash should be sorted on count and created_of and look like this hash:

{
  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}
}

Upvotes: 0

Views: 162

Answers (2)

sylvain.joyeux
sylvain.joyeux

Reputation: 1699

In Ruby 1.8, you cannot sort a hash as a hash has no order. In Ruby 1.9, a hash iteration order is defined by the insertion order. You therefore have to create a new hash in which you will insert the elements in the right order.

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

Upvotes: 2

tokland
tokland

Reputation: 67850

Assuming you are using Ruby 1.9 where hashes have order:

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

Upvotes: 3

Related Questions