Create month end dates for the last 12 months

I need a method that generates an array containing the end date of the month for each of the last 12 months. I came up with a solution below. However, this works, perhaps a more elegant way to solve this problem. Any suggestions? Is there a more efficient way to create 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 
+4
source share
4 answers

Usually, when you want an array of things to think about map . Although you are on this, why not generalize such a method so that you can return any n months that 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] 
+7
source
 require 'active_support/time' def months (1..12).map{|i| (Date.today - i.month).end_of_month} end 
+4
source

There is no specific method, but it may be an option:

 (1..12).map { |i| (Date.today - i.month).end_of_month } 

Nothing special, but it does the job.

+2
source
 require 'active_support/time' (1..12).map do |m| m.months.ago.end_of_month end 

Please note that if you want the correct month order, you must also call back

+1
source

Source: https://habr.com/ru/post/1492576/


All Articles