Generate month end dates for last 12 months

ruby, ruby-on-rails

Solution

Usually when you want an array of things start thinking about `map`. While you're at it why not generalize such a method so you can get back any `n` months you wish:

def last_end_dates(count = 12)
  count.times.map { |i| (Date.today - (i+1).month).end_of_month }
end
>> 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]

Problem

I need a method that generates an array containing the month end date for each of the past 12 months. I've come up with the solution below. It works, however, there's probably a more elegant way to solve this problem. Any suggestions? Is there a more efficient way to generate this array? Any advice would be greatly appreciated. ``` 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 ```

Original source