下面的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

它给出:
=> Fri, 01 Aug 2014
=> Mon, 01 Sep 2014
=> Wed, 01 Oct 2014
=> Sat, 01 Nov 2014
=> Mon, 01 Dec 2014

但是我怎么才能得到每个月的第一个星期四呢?即
=> Thu, 07 Aug 2014
=> Thu, 04 Sep 2014
=> Thu, 02 Oct 2014
=> Thu, 06 Nov 2014
=> Thu, 04 Dec 2014

最佳答案

只是为了好玩

class Date
  def skip_to_thursday
    # given current weekday, how many days we need to add for it to become thursday
    # for example, for monday (weekday 1) it's 3 days

    offset = lambda {|x| (4-x) % 7 }
    self + offset[wday]
  end
end


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

date.skip_to_thursday # => Thu, 03 Jul 2014

关于ruby-on-rails - 如何在Ruby/Rails中获得本月的第一个星期四?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24508787/

10-16 13:56