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
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):
Then from the start month, counting each month thereafter, find the first/last dates and append to an accumulator array.
Now
dates
will contain an array with nestedDate
pairs corresponding to the first and last date of each month. Thisdates
array will be easy to iterate for processing.This is tested and working in Rails 3.2.5/Ruby 1.9.3p194
Here's one way to do it:
=>