3
\$\begingroup\$

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?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.