Date
objects are also Comparable
, so you could construct a Range
:
@range = @date..(@date + 10)
You can iterate over it easily and output the results. If you want to access a particular date numerically, you can do:
@date_range = (@date..(@date + 10)).to_a
@date_range[1]
Or if you really need to format the dates beforehand, as in your example:
@date_range = (@date..(@date + 10)).map { |date| date.strftime("%Y-%m-%d") }
@date_range[1]
The final line would be equivalent in use to your @date_range[1]
(equal to tomorrow / @date + 1
), even though it is actually an Array
rather than a Hash
. A Hash
with sequential numeric keys doesn't make a lot of sense: you get those for free with an Array
and, as a bonus, the order of the values is preserved. In my opinion, using Range
s to start with slightly clarifies the intent, but it's not a spectacular difference.