ruby - Get last X month names in Rails -


i'm trying array of month names last 6 months. i've seen other posts address iterating , printing actual dates 7/1/16, 7/2/16, etc., nothing month names:

["february", "march", "april", "may", "june" ,"july"]

i trying following code, error:

@array = [] (6.months.ago..time.now).each |m|   @array.push(date::monthnames[m])   end   typeerror: can't iterate activesupport::timewithzone 

a uglier version builds on olives' answer, doesn't require looking dates in each month , 31x faster:

current_month = date.today.month  month_names = 6.downto(1).map { |n| datetime::monthnames.drop(1)[(current_month - n) % 12] } 

output when current_month 4 (to test dec-jan rollover):

["november", "december", "january", "february", "march", "april"]  

benchmark:

benchmark.measure   10000.times     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>  

compare cleaner version:

benchmark.measure   10000.times     5.downto(0).collect |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>  

Comments