2016-07-21 70 views
0

我試圖從過去6個月獲取一個月份名稱的數組。我已經看到其他帖子地址迭代和打印實際日期7/1/16,7/2/16等,但沒有隻是月份名稱:在Rails中獲取最近的X個月名稱

[「二月」,「三月」,「四月」,‘五一’,‘六一’,‘七一’]

我嘗試下面的代碼,但我得到這個錯誤:

@array = [] 
(6.months.ago..Time.now).each do |m| 
    @array.push(Date::MONTHNAMES[m]) 
end 

TypeError: can't iterate from ActiveSupport::TimeWithZone 

回答

3

是建立在Olives' answer,但並不需要仰視每個月的日期,大約是31X快稍微難看版本:

current_month = Date.today.month 

month_names = 6.downto(1).map { |n| DateTime::MONTHNAMES.drop(1)[(current_month - n) % 12] } 

輸出時current_month爲4(測試DEC-一月側翻):

["November", "December", "January", "February", "March", "April"] 

基準:

Benchmark.measure do 
    10000.times do 
    current_month = Date.today.month 
    month_names = 6.downto(1).map { |n| DateTime::MONTHNAMES.drop(1)[(current_month - n) % 12] } 
    end 
end 
=> #<Benchmark::Tms:0x007fcfda4830d0 @label="", @real=0.12975036300485954, @cstime=0.0, @cutime=0.0, @stime=0.07000000000000006, @utime=0.06999999999999984, @total=0.1399999999999999> 

比較來清潔版本:

Benchmark.measure do 
    10000.times do 
    5.downto(0).collect do |n| 
     Date::MONTHNAMES[n.months.ago.month] 
    end 
    end 
end 
=> #<Benchmark::Tms:0x007fcfdcbde9b8 @label="", @real=3.7730263769917656, @cstime=0.0, @cutime=0.0, @stime=0.04999999999999993, @utime=3.69, @total=3.7399999999999998> 
2

一個簡單的,雖然有點幼稚的方式,將遍歷整數並計算它落入哪個月份,然後最終在數組中查找它。

5.downto(0).collect do |n| 
    Date::MONTHNAMES[n.months.ago.month] 
end 

這將返回 ["February", "March", "April", "May", "June", "July"](這是在七月被執行)

相關問題