通常我只是反转结果数组:
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]