Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort hashmap of arrays by datetime from array

My hashmap 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 datetime if possible in RoR?

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

like image 565
Organiccat Avatar asked Oct 07 '12 18:10

Organiccat


2 Answers

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

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

An easy way to sort ascending:

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

To sort descending, you can use the full sort:

variable_name.sort {|vn1, vn2| vn2[:datetime] <=> vn1[:datetime]}
like image 133
Max Dunn Avatar answered Nov 16 '22 11:11

Max Dunn


It's possible to sort anything in Ruby, but keep in mind you'll end up with a sorted array. Although hashes have an internal order since Ruby 1.9, the Hash#sort 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 get 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 wouldn't be terribly difficult to map that back to a hash though.

like image 1
Peter Duijnstee Avatar answered Nov 16 '22 13:11

Peter Duijnstee