Reputation: 47
I have an array of datetime objects and i need to group objects by Date (day). How can I do t with pure ruby, without gems? For example, i have array
#<DateTime: 2015-03-04T01:30:00-06:00 ((2457086j,27000s,0n),-21600s,2299161j)>
#<DateTime: 2015-03-04T01:45:00-06:00 ((2457086j,27900s,0n),-21600s,2299161j)>
#<DateTime: 2015-03-04T04:00:00-06:00 ((2457086j,36000s,0n),-21600s,2299161j)>
#<DateTime: 2015-03-04T06:15:00-06:00 ((2457086j,44100s,0n),-21600s,2299161j)>
#<DateTime: 2015-03-03T07:30:00-06:00 ((2457086j,48600s,0n),-21600s,2299161j)>
#<DateTime: 2015-03-04T10:30:00-06:00 ((2457086j,59400s,0n),-21600s,2299161j)>
#<DateTime: 2015-03-04T11:30:00-06:00 ((2457086j,63000s,0n),-21600s,2299161j)>
#<DateTime: 2015-03-02T14:30:00-06:00 ((2457086j,73800s,0n),-21600s,2299161j)>
#<DateTime: 2015-03-04T16:00:00-06:00 ((2457086j,79200s,0n),-21600s,2299161j)>
And i need to group like
#<DateTime: 2015-03-02T14:30:00-06:00 ((2457086j,73800s,0n),-21600s,2299161j)>
-----------
#<DateTime: 2015-03-03T07:30:00-06:00 ((2457086j,48600s,0n),-21600s,2299161j)>
-----------
#<DateTime: 2015-03-04T01:30:00-06:00 ((2457086j,27000s,0n),-21600s,2299161j)>
#<DateTime: 2015-03-04T01:45:00-06:00 ((2457086j,27900s,0n),-21600s,2299161j)>
#<DateTime: 2015-03-04T04:00:00-06:00 ((2457086j,36000s,0n),-21600s,2299161j)>
#<DateTime: 2015-03-04T06:15:00-06:00 ((2457086j,44100s,0n),-21600s,2299161j)>
#<DateTime: 2015-03-04T10:30:00-06:00 ((2457086j,59400s,0n),-21600s,2299161j)>
#<DateTime: 2015-03-04T11:30:00-06:00 ((2457086j,63000s,0n),-21600s,2299161j)>
#<DateTime: 2015-03-04T16:00:00-06:00 ((2457086j,79200s,0n),-21600s,2299161j)>
Upvotes: 1
Views: 1119
Reputation: 118289
This is what you want:
require 'date'
# if you want day of the month
array_of_datetimes.group_by(&:day)
# if you want the day of week
array_of_datetimes.group_by(&:wday)
Look at the method Date#day
.
Well, as Stefan addressed, OP wanted something else. But I didn't get it from the question of OP. Anyway, this is what the OP wanted finally :
array_of_datetimes.group_by(&:to_date)
Upvotes: 5
Reputation: 1150
You can use group_by
from Enumerable
module. See http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-group_by for more detail.
array.group_by do |datetime|
"#{datetime.year}#{datetime.month}#{datetime.day}"
end
# => { "2015-03-03" => [...], "2015-03-04" => [...] }
Upvotes: 1