Olives' answer을 기반으로하지만, 각 달의 날짜를 찾고 필요로하지 않는 약 31 배 빠른입니다
약간 추악한 버전 :
current_month = Date.today.month
month_names = 6.downto(1).map { |n| DateTime::MONTHNAMES.drop(1)[(current_month - n) % 12] }
출력 current_month
는 4 (12 월 월 롤오버를 테스트하는)
["November", "December", "January", "February", "March", "April"]
벤치 마크 :
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>
:
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>
이 청소기 버전 비교