我编写了一个方法,如果间隔的开始等于另一个间隔的结束,则用另一个日期间隔合并一个日期间隔。
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
我认为这更具可读性:
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
您可以使用此 gem 将运算符添加到 范围 :
# 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