1

如果我有两个日期,即。

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

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

有什么建议么?

4

2 回答 2

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

另外,我不确定 Range#any 是否?是否实例化一个数组。以防万一,最好添加额外的检查以避免高内存消耗请参阅下面的更新):

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

并确保签入是<=结帐。

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
于 2013-03-20T14:02:26.673 回答
2

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

但你也可以这样做,

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

仅供参考,@DNNX 和 Aleks,当我们在 DateRange 上应用它时,我们必须将 Date 作为一个参数来覆盖。

于 2013-03-20T14:20:44.773 回答