生成过去12个月的月末日期

Ben*_*ney 5 ruby ruby-on-rails

我需要一个方法来生成一个包含过去12个月中每个月的结束日期的数组.我想出了下面的解决方案.然而,它的工作方式可能更为优雅,可以解决这个问题.有什么建议?有没有更有效的方法来生成这个数组?任何建议将不胜感激.

require 'active_support/time'

...

def months
  last_month_end = (Date.today - 1.month).end_of_month
  months = [last_month_end]
  11.times do
    month_end = (last_month_end - 1.month).end_of_month
    months << month_end
  end
  months
end
Run Code Online (Sandbox Code Playgroud)

Cas*_*per 8

通常当你想要一系列事情开始思考时map.虽然你在为什么不推广这样的方法,所以你可以回到任何n你想要的月份:

def last_end_dates(count = 12)
  count.times.map { |i| (Date.today - (i+1).month).end_of_month }
end
Run Code Online (Sandbox Code Playgroud)

>> pp last_end_dates(5)

[Sun, 30 Jun 2013,
 Fri, 31 May 2013,
 Tue, 30 Apr 2013,
 Sun, 31 Mar 2013,
 Thu, 28 Feb 2013]
Run Code Online (Sandbox Code Playgroud)