是建立在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>