Iterating a Date Range in Ruby by Day

I wanted to take a date range and iterate over it to produce results by day, but when I went to check the results, there were results by second.

def my_date_thing(a_range)
  a_range.each do |date|
     # something interesting by date
  end
end
 
my_date_thing(10.days.ago .. 0.days.ago)

Turns out, that by default those cool days.ago methods return DateTime objects not Date objects. DateTime objects iterate by seconds, not by days.

But here’s a quick fix: ensure that the range is based on dates first

def my_date_thing(a_range)
  a_range = (a_range.begin.to_date .. a_range.end.to_date)
  a_range.each do |date|
     # something interesting by date
  end
end
 
my_date_thing(10.days.ago .. 0.days.ago)

Now, the range a_range will always iterate by day.

Leave a Reply

Your email address will not be published. Required fields are marked *