HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyrailsMinor

Array of date by each week

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arrayweekeachdate

Problem

I have two dates, example :

date1 = "4-02-2017".to_date
date2 = "4-02-2017".to_date + 29


I try to get array of date by each week with this :

(date1..date2).select{|x| Date::DAYNAMES[x.wday] == Date::DAYNAMES[date1.wday] }


Rersult :

[Sat, 04 Feb 2017, 
 Sat, 11 Feb 2017,
 Sat, 18 Feb 2017, 
 Sat, 25 Feb 2017,
 Sat, 04 Mar 2017]


Is there a better way to solve the case other than the way as above?

Solution

There's no reason to look up the day's name in the DAYNAMES array. You already have the wday values, so you can just compare those directly.

I.e. if

Date::DAYNAMES[x] == Date::DAYNAMES[y]


it follows that

x == y


so:

(date1..date2).select { |date| date.wday == date1.wday }


Or, simpler, you can specify a step for the range and just skip one week at a time:

(date1..date2).step(7).to_a


Now, a week is typically 7 days long, but there have been a few cases of nations choosing to officially move to the other side of the international dateline, causing a week to not be 7 days long in their calendar. It's rare of course, but something to be aware of.

Code Snippets

Date::DAYNAMES[x] == Date::DAYNAMES[y]
(date1..date2).select { |date| date.wday == date1.wday }
(date1..date2).step(7).to_a

Context

StackExchange Code Review Q#154418, answer score: 2

Revisions (0)

No revisions yet.