Reputation: 7409
How could I group by time(HH:MM) with mongoid or ruby
I want to group by the following data by departure_at
(HH:MM).
How to get it easier with Rails or Mongoid
Expect result:
{
'06:40': [item125, item131],
'10:20': [item126],
....
[125] #<Tiger _id: 811_0640_1010_TPE_KIX, to: "KIX", from: "TPE", price: 4899,departure_at: 08-11 06:40:00 UTC>,
[126] #<Tiger _id: 811_1020_0305_TPE_KIX, to: "KIX", from: "TPE", price: 5450,departure_at: 08-11 10:20:00 UTC>,
....
[131] #<Tiger _id: 812_0640_1010_TPE_KIX, to: "KIX", from: "TPE", price: 4899,departure_at: 08-12 06:40:00 UTC>,
Upvotes: 0
Views: 62
Reputation: 13999
First, make an array of ["HH:MM", object]
. Then you can use the trick from this question
array = @your_objects.map{|obj| [obj.date_departure.strftime("%H:%m"), obj]}
Hash[ array.group_by(&:first).map{ |k,a| [k,a.map(&:last)] } ]
Upvotes: 1