如何在Ruby / Rails中获得本月的第一个星期四?

dwk*_*kns 2 ruby ruby-on-rails

以下Ruby代码让我每个月的第一天:

require 'active_support/all'

# get the date at the beginning of this month
date = Date.today.beginning_of_month

# get the first day of the next 5 months
5.times do |num|
  date = date.next_month
  p date
end
Run Code Online (Sandbox Code Playgroud)

这使 :

=> Fri, 01 Aug 2014
=> Mon, 01 Sep 2014
=> Wed, 01 Oct 2014
=> Sat, 01 Nov 2014
=> Mon, 01 Dec 2014
Run Code Online (Sandbox Code Playgroud)

但是,如何获得每月的第一个星期四?即

=> Thu, 07 Aug 2014
=> Thu, 04 Sep 2014
=> Thu, 02 Oct 2014
=> Thu, 06 Nov 2014
=> Thu, 04 Dec 2014
Run Code Online (Sandbox Code Playgroud)

And*_*rao 6

无需迭代或条件即可获得到下周四的所谓天数增量:

#4 is thursday because wday starts at 0 (sunday)

date = Date.today.beginning_of_month
date += (4 - date.wday) % 7
p date
=> Thu, 03 Jul 2014
Run Code Online (Sandbox Code Playgroud)