如何在 Ruby 中获得两个日期之间的所有星期日?

如何在 Ruby 中获得两个日期之间的所有星期日?

问题描述:

我正在处理一个表单,用户可以在其中输入日期范围并从复选框列表中选择一周中的一天/几天,即星期日、星期一、星期二、星期三、星期四、星期五和星期六.

I'm working on a form where the user enters a date range and selects from a list of checkboxes a day/days of the week i.e Sunday, Monday, Tuesday, Wednesday, Thursday, Friday and saturday.

提交表单后,我需要一种方法来获取基于所选日期输入的两个日期之间的日期列表,即给定的两个日期之间的所有星期一和星期四.我已经浏览了文档,但无法确定如何有效地执行此操作,即 ruby​​ 方式.

Once the form is submitted I need a way to grab a list of dates between the two dates entered based upon the days that were chosen i.e All Mondays and Thursdays between the two dates given. I've looked through the docs but can't pin point how to do this efficiently i.e the ruby way.

有趣的一个!:D

 start_date = Date.today # your start
 end_date = Date.today + 1.year # your end
 my_days = [1,2,3] # day of the week in 0-6. Sunday is day-of-week 0; Saturday is day-of-week 6.
 result = (start_date..end_date).to_a.select {|k| my_days.include?(k.wday)}

使用上面的数据,您将获得从现在到明年之间所有周一/周二/周三的数组.

using the data above you'll get an array of all Mon/Tue/Weds between now and next year.