You can sort something in Ruby, but keep in mind that you end up with a sorted array. Although hashes have an internal order since Ruby 1.9, the Hash # sorting method still returns an array.
For example:
hash = { user1: { name: 'Baz', date: Time.current }, user2: { name: 'Bar', date: Time.current - 1.month }, user3: { name: 'Foo', date: Time.current - 2.months }, } hash.sort { |x, y| x.last[:date] <=> y.last[:date] }
will give you the result:
[ [:user3, {:name=>"Foo", :date=>Tue, 07 Aug 2012 20:32:23 CEST +02:00}], [:user2, {:name=>"Bar", :date=>Fri, 07 Sep 2012 20:32:23 CEST +02:00}], [:user1, {:name=>"Baz", :date=>Sun, 07 Oct 2012 20:32:23 CEST +02:00}] ]
It would not be so difficult to compare this with a hash, though.
Peter Duijnstee
source share