ruby on rails - Generate month end dates for last 12 months -


i need method generates array containing month end date each of past 12 months. i've come solution below. works, however, there's more elegant way solve problem. suggestions? there more efficient way generate array? advice appreciated.

require 'active_support/time'  ...  def months   last_month_end = (date.today - 1.month).end_of_month   months = [last_month_end]   11.times     month_end = (last_month_end - 1.month).end_of_month     months << month_end   end   months end 

usually when want array of things start thinking map. while you're @ why not generalize such method can n months 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] 

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -