6

I'm writing a method that iterates using dates given a start and end date, and I need to the date within the loop. Something like this:

start_date = 2013/03/12
end_date = 2013/11/20

# from start_date to end_date do |f|
  puts date_this_iteration_is_processing
end

Can someone please help me with this?

I've read these questions, but they didn't indicate how to determine the date that the given iteration is on.

How to Loop through Months in Ruby on Rails Iterating the dates in ruby on rails

Community
  • 1
  • 1
yellowreign
  • 3,528
  • 8
  • 43
  • 80

3 Answers3

14

is this what you are looking for? use the range operator ..

start_date = Date.parse('2013-03-12')
end_date = Date.parse('2013-11-20')

(start_date..end_date).each do |day|
  puts day
end
Thomas Klemm
  • 10,678
  • 1
  • 51
  • 54
house9
  • 20,359
  • 8
  • 55
  • 61
3

You can use upto

start_date = Date.parse('2019-05-20')
end_date = Date.parse('2019-05-22')

(start_date).upto(end_date).each do |day|
  puts day
end
2

In a less static fashion:

(Date.today - 60.days..Date.today).each do |day|
  puts day
end