如何在Ruby on Rails中循环浏览数月 [英] How to Loop through Months in Ruby on Rails

查看:74
本文介绍了如何在Ruby on Rails中循环浏览数月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Ruby on Rails应用程序中浏览几个月.对于每个月,我需要找到该月的第一天和最后一天.然后将这些日期用于单独的查询中,以查找在这些日期期间发生的事件并对其进行计算.

I need to loop through several months in a Ruby on Rails application. For each month, I need to find the first and last day of that given month. These dates are then used in a separate query to find events occurring during those dates and running calculations on them.

最初,我尝试过类似的操作:

Initially, I tried something like:

(11.months.ago.to_date.month..Date.today.month).each do |m|
  start_date = '01-#{m}-#{Date.today.year}'.to_date.beginning_of_month
  end_date = '01-#{m}-#{Date.today.year}'.to_date.end_of_month
end

当然,在11个月前涉及到上一年的情况下,这种情况下的年份不会更新.而且,我不认为这种for/each循环有效.我还尝试将数字映射到数组并使用相同的方法,但收到错误.

Of course, the year isn't updated in this case in the event that 11 months ago involves going back to the previous year. And, I don't think this type of for/each loop works. I also tried mapping the numbers to an array and using the same method, but received an error.

完成这样的最佳方法是什么?

What's the best way to accomplish something like this?

推荐答案

首先,计算两个日期之间的月份数(

First, count the number of months between two dates (courtesy of Massimiliano Peluso):

start_date = 13.months.ago.to_date
# => Wed, 16 Nov 2011

end_date = Date.today
# => Sun, 16 Dec 2012

number_of_months = (end_date.year*12+end_date.month)-(start_date.year*12+start_date.month)
# => 13

然后从开始的月份开始,然后计算每个月的日期,找到第一个/最后一个日期并追加到累加器数组中.

Then from the start month, counting each month thereafter, find the first/last dates and append to an accumulator array.

dates = number_of_months.times.each_with_object([]) do |count, array|
  array << [start_date.beginning_of_month + count.months,
            start_date.end_of_month + count.months]
end
# => ...

现在,dates将包含一个数组,该数组具有嵌套的Date对,分别对应于每个月的第一个和最后一个日期.该dates数组将易于迭代进行处理.

Now dates will contain an array with nested Date pairs corresponding to the first and last date of each month. This dates array will be easy to iterate for processing.

dates
# => [[Tue, 01 Nov 2011, Wed, 30 Nov 2011], [Thu, 01 Dec 2011, Fri, 30 Dec 2011], ...

dates[0].first
# => Tue, 01 Nov 2011

dates[0].last
# => Wed, 30 Nov 2011

dates[0].last.class
# => Date

这已在Rails 3.2.5/Ruby 1.9.3p194中经过测试并可以正常工作

This is tested and working in Rails 3.2.5/Ruby 1.9.3p194

这篇关于如何在Ruby on Rails中循环浏览数月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆