如果间隔的开始等于另一个间隔的结束,我已经写了一个方法来合并日期间隔和另一个日期间隔。
def merge
slots.each do |slot|
if self.start == slot.end
slot.end = self.end
slot.save
return self
elsif self.end == slot.start
slot.start = self.start
slot.save
return self
end
end
self.save
end
self
是我想要将其与slots
数组中存在的任何区间合并的区间。
重构这种方法的最佳方法是什么?
我试图把它变成这样的东西但没有成功:
def merge
slots.each do |slot|
if slot.one_bound == slot.other_bound
slot.other_bound = self.other_bound
slot.save
return self
end
end
self.save
end
答案 0 :(得分:0)
我认为这更具可读性:
def merge
slots.each do |slot|
if start_the_same_as_end_for?(slot)
slot.end = self.end
elsif end_the_same_as_start_for?(slot)
slot.start = self.start
end
slot.save
end
end
private
def start_the_same_as_end_for?(slot)
self.start == slot.end
end
def end_the_same_as_start_for?(slot)
self.end == slot.start
end
答案 1 :(得分:0)
您可以使用此gem向Range添加运算符:
# gem install range_operators
require 'date'
require 'range_operators'
range1 = Date.new(2014, 5, 10) .. Date.new(2014, 8, 10)
range2 = Date.new(2014, 8, 10) .. Date.new(2014, 8, 20)
range3 = Date.new(2014, 8, 11) .. Date.new(2014, 8, 20)
puts range1 + range2
#=> 2014-05-10..2014-08-20
作为奖励,如果第二个范围恰好在第一个范围之后,它也有效:
puts range1 + range3
#=> 2014-05-10..2014-08-20
请注意Range#
返回范围数组。如果此数组只有一个元素,则表示范围已合并:
result = range1 + range2
if result.size == 1 then
# save result.first
end