2016-07-21 3 views
0

지난 6 개월 간의 월 이름 배열을 얻으려고합니다. 나는 실제 날짜가 7/1/16, 7/2/16 등 반복 및 인쇄되는 다른 게시물을 보았지만 그저 월 이름을 사용하는 것은 아무것도 없습니다.레일에서 마지막 X 달 이름 가져 오기

[ "February", "March", " 에이프릴 ","월 ","6월 ","7 월 "]

나는 다음과 같은 코드를 시도했다, 그러나 나는이 오류 얻을 :

@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을 기반으로하지만, 각 달의 날짜를 찾고 필요로하지 않는 약 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> 

이 청소기 버전 비교

2

간단한을 조금 순진 방법이 있지만, 것 정수를 반복하고 어떤 달에 해당하는지 계산 한 다음 마지막으로 배열에서 조회합니다.

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

이 (이 7 월에 실행중인) ["February", "March", "April", "May", "June", "July"]를 반환합니다

관련 문제