Ruby日期范围包括特定日期

时间:2013-03-20 13:54:48

标签: ruby-on-rails ruby date

如果我有两个日期,即

checkin = Date.parse('params[:checkin])
checkout = Date.parse('params[:checkout])

如何检查这两个日期之间是否有星期一?

有什么建议吗?

2 个答案:

答案 0 :(得分:6)

  (checkin..checkout).any?(&:monday?)

另外,我不确定Range#是否?是否实例化数组。 如果确实如此,最好添加额外的检查以避免高内存消耗参见下面的更新):

  checkout - checkin > 7 || (checkin..checkout).any?(&:monday?)

并确保checkin为< = checkout。

UPD:我刚刚经过双重检查。没有必要检查checkout - checkin是否大于某些东西。 Range#any?足够聪明并且不会在内部创建数组(至少在ruby 1.9.3中):

1.9.3p327 :004 > checkin, checkout = Date.new, Date.new + 9000.years
=> [Mon, 01 Jan -4712, Sun, 01 Jan 4288]

1.9.3p327 :005 > `ps -o vsize= #{$$}`.strip.to_i
 => 3161660   # memory usage of the current process 

1.9.3p327 :006 > (checkin..checkout).any?(&:monday?)
 => true
1.9.3p327 :007 > `ps -o vsize= #{$$}`.strip.to_i
 => 3161660   # memory usage of the current process stays the same

1.9.3p327 :008 > (checkin..checkout).to_a.any?(&:monday?) # force .to_a
 => true
1.9.3p327 :009 > `ps -o vsize= #{$$}`.strip.to_i
 => 3421680   # memory usage increases and also the previous line was very slow

答案 1 :(得分:2)

这个答案是awsum, (checkin..checkout).any?(&:monday?)

但你也可以这样做,

(checkin..checkout).cover?(Date.today) # you can give date to it.

仅限于FYI,@ DNNX和Aleks,我们必须将Date作为参数覆盖,因为我们在DateRange上应用它。