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?
1 Answer 1
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.