user984621 user984621 - 19 days ago 6
Ruby Question

Loop through years + months

I am trying to loop through years and months. If

@user.created_at
is
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[(@user.created_at.month..Date.today.month).map { |month| [ month, 0 ] }].merge(...)


But the above code returns


stack level too deep


because it loops
11..3
.
How can I figure out this issue?

Answer

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 = Date.today.beginning_of_month
hash = { }

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

  date = date.advance(months: 1)
end