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 :

[2017年2月04日, 
 2017年2月11日,
 2017年2月18日, 
 2017年2月25日,
 2017年3月04日]

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

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Feb 4, 2017 at 3:42
\$\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.

answered Feb 4, 2017 at 13:02
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.