Ruby on Rails开发中如何优化循环效率,避免数月重复问题?

更新于
2026-10-09 18:27:06
1阅读来源:SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计285个文字,预计阅读时间需要2分钟。

Ruby on Rails开发中如何优化循环效率,避免数月重复问题?

我尝试了以下方法:如果@user.created_at是2015年11月,那么我希望输出如下:November 2015 December 2015 January 2016 February 2016 March 2016。我尝试了以下方法:+ Hash[(@ + user.created_at.month..Date.today.month)]

我试图循环数年和数月.如果@ user.created_at是2015年11月,那么我想得到这个输出:

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:

Ruby on Rails开发中如何优化循环效率,避免数月重复问题?

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

本文共计285个文字,预计阅读时间需要2分钟。

Ruby on Rails开发中如何优化循环效率,避免数月重复问题?

我尝试了以下方法:如果@user.created_at是2015年11月,那么我希望输出如下:November 2015 December 2015 January 2016 February 2016 March 2016。我尝试了以下方法:+ Hash[(@ + user.created_at.month..Date.today.month)]

我试图循环数年和数月.如果@ user.created_at是2015年11月,那么我想得到这个输出:

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:

Ruby on Rails开发中如何优化循环效率,避免数月重复问题?

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