0

c should be inner period of 2 periods. How to get it in most elegant way?

a1=Date.current
a2=Date.current + 2.months

b1=Date.current + 1.month
b2=Date.current + 3.months

c=???

c.should_be [Date.current + 1.month, Date.current + 2.months]
Arnis Lapsa
  • 45,880
  • 29
  • 115
  • 195

2 Answers2

2

Hurried implementation:

xs = (a1..a2).to_a & (b1..b2).to_a
(xs.first..xs.last)
# => Sun, 24 Jun 2012..Tue, 24 Jul 2012

There is nothing special about a range of dates. So search "range intersection" to do it more efficiently (for example here). Now you can write:

(a1..a2) & (b1..b2)
Community
  • 1
  • 1
tokland
  • 66,169
  • 13
  • 144
  • 170
0
d= [a1, a2, b1, b2]
[*1..d.length/ 2].map do |dt| 
    d.shift(2) 
end.map do |dx| 
    Date.current+ (dx[1]- dx[0]) 
end

[Sun, 24 Jun 2012, Tue, 24 Jul 2012]

nurettin
  • 11,090
  • 5
  • 65
  • 85