1

我有一个问题,红宝石代码:

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]
4

1 回答 1

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
于 2012-05-04T07:22:50.370 回答