我有一个问题,ruby代码:
def give_me_all_periods(period, paid_periods)
# Can you help me?
end
period = [1..10]
paid_periods = [1..2, 5..8]
give_me_all_periods(period, paid_periods).should == [1...2, 2...5, 5...8, 8...10]
答案 0 :(得分:1)
def give_me_all_periods(period, paid_periods)
p = period | paid_periods
union = p.inject([]){|u,x| u = u|range_to_arr(x)}.sort
ranges =[]
union.each_cons(2){|a| ranges << Range.new(a[0],a[1]) }
ranges
end
def range_to_arr(r)
[r.first,r.last]
end