我有一个日期范围,我希望能够反向循环。给出以下内容,我将如何实现此目标,标准Range
运算符似乎无法正常工作。
>> sd = Date.parse('2010-03-01')
=> Mon, 01 Mar 2010
>> ed = Date.parse('2010-03-05')
=> Fri, 05 Mar 2010
>> (sd..ed).to_a
=> [Mon, 01 Mar 2010, Tue, 02 Mar 2010, Wed, 03 Mar 2010, Thu, 04 Mar 2010, Fri, 05 Mar 2010]
>> (ed..sd).to_a
=> []
如您所见,范围运算符从头到尾正常工作,但不是从头到尾。
答案 0 :(得分:62)
尝试上/下:
irb(main):003:0> sd = Date.parse('2010-03-01')
=> #<Date: 4910513/2,0,2299161>
irb(main):004:0> ed = Date.parse('2010-03-15')
=> #<Date: 4910541/2,0,2299161>
irb(main):005:0> sd.upto(ed) { |date| puts date }
2010-03-01
2010-03-02
2010-03-03
2010-03-04
2010-03-05
2010-03-06
2010-03-07
2010-03-08
2010-03-09
2010-03-10
2010-03-11
2010-03-12
2010-03-13
2010-03-14
2010-03-15
=> #<Date: 4910513/2,0,2299161>
irb(main):006:0> ed.downto(sd) { |date| puts date }
2010-03-15
2010-03-14
2010-03-13
2010-03-12
2010-03-11
2010-03-10
2010-03-09
2010-03-08
2010-03-07
2010-03-06
2010-03-05
2010-03-04
2010-03-03
2010-03-02
2010-03-01
=> #<Date: 4910541/2,0,2299161>
答案 1 :(得分:6)
我通常只是反转生成的数组:
ruby-1.8.7-p72 > sd = Date.parse('2010-03-01')
=> Mon, 01 Mar 2010
ruby-1.8.7-p72 > ed = Date.parse('2010-03-05')
=> Fri, 05 Mar 2010
ruby-1.8.7-p72 > (sd..ed).to_a
=> [Mon, 01 Mar 2010, Tue, 02 Mar 2010, Wed, 03 Mar 2010, Thu, 04 Mar 2010, Fri, 05 Mar 2010]
ruby-1.8.7-p72 > (sd..ed).to_a.reverse
=> [Fri, 05 Mar 2010, Thu, 04 Mar 2010, Wed, 03 Mar 2010, Tue, 02 Mar 2010, Mon, 01 Mar 2010]
我想,当你不知道开始日期是在结束日期之前还是之后,为了让它做正确的事情,你需要的是:
def date_range(sd, ed)
sd < ed ? (sd..ed).to_a : (ed..sd).to_a.reverse
end
这将为你提供正确的选择:
ruby-1.8.7-p72 > sd = Date.parse('2010-03-01')
=> Mon, 01 Mar 2010
ruby-1.8.7-p72 > ed = Date.parse('2010-03-05')
=> Fri, 05 Mar 2010
ruby-1.8.7-p72 > date_range(sd, ed)
=> [Mon, 01 Mar 2010, Tue, 02 Mar 2010, Wed, 03 Mar 2010, Thu, 04 Mar 2010, Fri, 05 Mar 2010]
ruby-1.8.7-p72 > date_range(ed, sd)
=> [Fri, 05 Mar 2010, Thu, 04 Mar 2010, Wed, 03 Mar 2010, Tue, 02 Mar 2010, Mon, 01 Mar 2010]