Ruby:两个范围之间的交集

在ruby中,给定两个日期范围,我想要表示两个日期范围的交集的范围,如果没有交点,则为零.例如:
(Date.new(2011,1,1)..Date.new(2011,15)) & (Date.new(2011,10)..Date.new(2011,2,15))
=> Mon,10 Jan 2011..Sat,15 Jan 2011

编辑:应该说我希望它适用于DateTime,所以间隔可以缩短到mins和secs:

(DateTime.new(2011,22,45)..Date.new(2011,15))
=> Sat,01 Jan 2011 22:45:00 +0000..Tue,15 Feb 2011

解决方法

require 'date'

class Range
  def intersection(other)
    return nil if (self.max < other.begin or other.max < self.begin) 
    [self.begin,other.begin].max..[self.max,other.max].min
  end
  alias_method :&,:intersection
end

p (Date.new(2011,15))
#<Date: 2011-01-10 ((2455572j,0s,0n),+0s,2299161j)>..#<Date: 2011-01-15 ((2455577j,2299161j)>

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...