user984621 user984621 - 1 year ago 69
Ruby Question

Loop through years + months

I am trying to loop through years and months. If

November 2015
, then I'd like to get this output:

November 2015
December 2015
January 2016
February 2016
March 2016

I tried the following:

Hash[( { |month| [ month, 0 ] }].merge(...)

But the above code returns

stack level too deep

because it loops
How can I figure out this issue?

Answer Source

If you want to compute the upcoming months/years you could always use advance:

start = @user.created_at.to_date.beginning_of_month

Hash[(0..6).collect { |n| [ start.advance(months: n).month, 0 ] }]

That should properly step through days/months. You may want to just stick in dates instead of just the month number.

If you want to do "up to today" then try this:

date = @user.created_at.to_date.beginning_of_month
stop =
hash = { }

while (date <= stop)
  hash[date] = 0

  date = date.advance(months: 1)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download