I have 2 date ranges, start_date1..end_date1
and start_date2..end_date2
, is there an easy "ruby" way to find all the dates that are in both ranges?
Asked
Active
Viewed 244 times
2

Russ Bradberry
- 10,705
- 17
- 69
- 85
1 Answers
3
You can use
(start_date1..end_date1).to_set & (start_date2..end_date2).to_set
here's a fully worked example:
require 'date'
require 'set'
((Date.today - 3)..(Date.today + 2)).to_set & (Date.today..(Date.today + 5)).to_set
if you're counting characters, you can also just do
(start_date1..end_date1).to_set & start_date2..end_date2
but I think the original version is clearer.

Peter
- 127,331
- 53
- 180
- 211
-
Using `to_a` instead of `to_set` will be a bit faster and should yield the same result. – the Tin Man Jan 06 '12 at 23:41