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
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]}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With