Ruby:两个范围之间的交集 [英] Ruby: intersection between two ranges
本文介绍了Ruby:两个范围之间的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
(Date.new(2011,1,1).. Date.new(2011,1,15) )& (Date.new(2011,1,10).. Date.new(2011,2,15))
=>星期一,2011年1月10日..Sat,2011年1月15日
编辑:应该说我想要为DateTime也工作,所以间隔可以缩短到mins和secs:
(DateTime.new(2011,1, 1,22,45).. Date.new(2011,2,15))& (Date.new(2011,1,1).. Date.new(2011,2,15))
=>星期六,2011年1月01日22:45:00 + 0000..Tue,2011年2月15日
解决方案
require'date'
class Range
def intersection(other)
return nil if(self。 max< other.begin或other.max< self.begin)
[self.begin,other.begin] .max .. [self.max,other.max] .min
end
alias_method:&:intersection
end
p(Date.new(2011,1,1).. Date.new(2011,1,15))& (Date.new(2011,1,10).. Date.new(2011,2,15))
#< Date:2011-01-10((2455572j,0s,0n),+ 0s, 2299161j)> ..<日期:2011-01-15((2455577j,0s,0n),+ 0s,2299161j)>
In ruby, given two date ranges, I want the range that represents the intersection of the two date ranges, or nil if no intersection. For example:
(Date.new(2011,1,1)..Date.new(2011,1,15)) & (Date.new(2011,1,10)..Date.new(2011,2,15))
=> Mon, 10 Jan 2011..Sat, 15 Jan 2011
Edit: Should have said that I want it to work for DateTime as well, so interval can be down to mins and secs:
(DateTime.new(2011,1,1,22,45)..Date.new(2011,2,15)) & (Date.new(2011,1,1)..Date.new(2011,2,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,1,1)..Date.new(2011,1,15)) & (Date.new(2011,1,10)..Date.new(2011,2,15))
#<Date: 2011-01-10 ((2455572j,0s,0n),+0s,2299161j)>..#<Date: 2011-01-15 ((2455577j,0s,0n),+0s,2299161j)>
这篇关于Ruby:两个范围之间的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文