I don't know if this is the easiest (or best) way, but it seems to work:
require 'date' # from stdlib
# => true
(Date.parse('2006-04-01')..Date.parse('2006-04-23')).to_a.map { |e| e.to_s }
# => ["2006-04-01",
"2006-04-02",
"2006-04-03",
"2006-04-04",
...,
"2006-04-23"]
You can do a similar thing with Time to get different ranges (hours,
half-days, etc.) but it's pretty wasteful in terms of efficiency so
stick with date if you can.
a =
# =>
(Time.parse('2006-4-23')..Time.parse('2006-4-27')).step(86400) { |t| a << t }
# => Sun Apr 23 00:00:00 BST 2006..Thu Apr 27 00:00:00 BST 2006
a
# => [Sun Apr 23 00:00:00 BST 2006,
# Mon Apr 24 00:00:00 BST 2006,
# Tue Apr 25 00:00:00 BST 2006,
# Wed Apr 26 00:00:00 BST 2006,
# Thu Apr 27 00:00:00 BST 2006]
a =
# =>
(Time.parse('2006-4-23')..Time.parse('2006-4-27')).step(3600) { |t| a << t }
# => Sun Apr 23 00:00:00 BST 2006..Thu Apr 27 00:00:00 BST 2006
a
# => [Sun Apr 23 00:00:00 BST 2006,
# Sun Apr 23 01:00:00 BST 2006,
# Sun Apr 23 02:00:00 BST 2006,
# Sun Apr 23 03:00:00 BST 2006,
# Sun Apr 23 04:00:00 BST 2006,
# Sun Apr 23 05:00:00 BST 2006,
# ... 97 elements ... ]
···
On Sun, 2006-04-23 at 20:58 +0900, Marston A. wrote:
What is the easiest way in Ruby to make an array our of a date range?
Something like this:
@date1 = "2006-04-01"
@date2 = "2006-04-23"
array = [@date1..@date2]
Something like that would be an easy solution as @date1 and @date2 are
going to by dynamic, but this doesn't work as they are strings.
Or would I have to manually insert the ranges one by one myself?
array = ["2006-04-01", "2006-04-02", ... , "2006-04-23"]
Thanks for any help in advanced!
--
Ross Bamford - rosco@roscopeco.REMOVE.co.uk