Chris Kong
Chris Kong

Reputation: 399

ruby: group an array of dates into a hash based on which week they are with key as the first date in each week

For example, I have

['2013-12-29', '2013-12-31', '2014-01-04', '2014-01-11', '2014-01-15']

I expect the output as

{'2013-12-29'=>['2013-12-29', '2013-12-31', '2014-01-04'], '2014-01-05' => ['2014-01-11'], '2014-01-12' => ['2014-01-15']}

I tried %U, but it doesn't meet my requirement since it will consider the last week of last year is a different week from the first week of this year.

Upvotes: 2

Views: 1229

Answers (1)

falsetru
falsetru

Reputation: 369094

Using Enumerable#group_by:

require 'date'
a = ['2013-12-29', '2013-12-31', '2014-01-04', '2014-01-11', '2014-01-15']
a.group_by { |x|
  day = Date.strptime(x, '%Y-%m-%d')
  (day - day.wday).strftime('%Y-%m-%d')
}
# => {"2013-12-29"=>["2013-12-29", "2013-12-31", "2014-01-04"],
#     "2014-01-05"=>["2014-01-11"],
#     "2014-01-12"=>["2014-01-15"]}

Upvotes: 8

Related Questions