2013-07-21 51 views
4

我需要一種方法來生成包含過去12個月的每個月的結束日期的數組。我已經拿出了下面的解決方案。它的工作原理,但是,可能有更好的方法來解決這個問題。有什麼建議麼?有沒有更有效的方法來生成這個數組?任何建議將不勝感激。生成最近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 

回答

7

通常當你想要一個事物的陣列開始思考map。當你在它爲什麼不能一概而論這樣的方法,讓你可以回到任何n個月你想:

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] 
+0

美麗。我喜歡它。這正是我所期待的。我之前玩過地圖,但通常我會嘗試從另一個地圖生成一個數組。謝謝你的幫助。 –

4
require 'active_support/time' 

def months 
    (1..12).map{|i| (Date.today - i.month).end_of_month} 
end 
2

沒有一個具體方法,這可能是一種選擇然而:

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

沒什麼特別的,但沒有工作。

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

注意,如果你想要個月的正確順序,你應該也稱反向

相關問題