Sort a hash array of arrays by time date from an array

My hash file is as follows:

variable_name[user] = { url, datetime } variable_name[user] << { url1, datetime1 } variable_name[user] << { url2, datetime2 } variable_name[user] << { url3, datetime3 } 

How can I sort this by date of time, if possible, in RoR?

edit: variable_name is the hash, [user] is the key. value is an array

+7
source share
2 answers

Assuming variable_name is an array, and you mean something like:

 variable_name[user] = {:url => url, :datetime => datetime } 

A simple way to sort in ascending order:

 variable_name.sort_by {|vn| vn[:datetime]} 

To sort in descending order, you can use full sort:

 variable_name.sort {|vn1, vn2| vn2[:datetime] <=> vn1[:datetime]} 
+11
source

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.

+1
source

All Articles