我试图循环数年和数月.如果@ user.created_at是2015年11月,那么我想得到这个输出: November 2015December 2015January 2016February 2016March 2016 我尝试了以下方法: Hash[(@user.created_at.month..Date.today.month
November 2015 December 2015 January 2016 February 2016 March 2016
我尝试了以下方法:
Hash[(@user.created_at.month..Date.today.month).map { |month| [ month, 0 ] }].merge(...)
但上面的代码返回
stack level too deep
因为它循环11..3.
我怎么能弄清楚这个问题呢?
advance
:
start = @user.created_at.to_date.beginning_of_month Hash[(0..6).collect { |n| [ start.advance(months: n).month, 0 ] }]
这应该适当地延长几天/几个月.您可能只想坚持日期而不仅仅是月份数.
如果你想做“到今天”,那试试这个:
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