Ruby日期计算

时间:2013-03-05 14:59:04

标签: ruby date

这不是我注意到的问题,而是想知道是否有人可以向我解释。

如果我使用内联类型语法,我会得到两个不同的,互换的答案:

irb(main):017:0> d = (Date.today >> 3) - (d.day + 1)
=> #<Date: 2013-06-01 ((2456445j,0s,0n),+0s,2299161j)>
irb(main):018:0> d = (Date.today >> 3) - (d.day + 1)
=> #<Date: 2013-06-03 ((2456447j,0s,0n),+0s,2299161j)>
irb(main):019:0> d = (Date.today >> 3) - (d.day + 1)
=> #<Date: 2013-06-01 ((2456445j,0s,0n),+0s,2299161j)>
irb(main):020:0> d = (Date.today >> 3) - (d.day + 1)
=> #<Date: 2013-06-03 ((2456447j,0s,0n),+0s,2299161j)>

如果我在多行上做同样的事情,我每次都会得到相同的正确答案:

irb(main):025:0> d = Date.today
=> #<Date: 2013-03-05 ((2456357j,0s,0n),+0s,2299161j)>
irb(main):026:0> d = d >> 3
=> #<Date: 2013-06-05 ((2456449j,0s,0n),+0s,2299161j)>
irb(main):027:0> d = d - d.day + 1
=> #<Date: 2013-06-01 ((2456445j,0s,0n),+0s,2299161j)>
irb(main):028:0> d = Date.today
=> #<Date: 2013-03-05 ((2456357j,0s,0n),+0s,2299161j)>
irb(main):029:0> d = d >> 3
=> #<Date: 2013-06-05 ((2456449j,0s,0n),+0s,2299161j)>
irb(main):030:0> d = d - d.day + 1
=> #<Date: 2013-06-01 ((2456445j,0s,0n),+0s,2299161j)>

为什么会发生这种情况的任何想法?我只是有兴趣了解,因为我看到它的方式,两种方式应该总是返回相同的答案。

2 个答案:

答案 0 :(得分:2)

这与Ruby的日期格式无关。

在右侧的每个表达式中评估d的时间。也就是说,在陈述评估开始时,而不是在评估期间:

d = 1
d = 1 + d + d
=> 3

d = 1
d = 1 + d
d = d + d
=> 4

答案 1 :(得分:1)

d.day是指d的现有值,因此当您更改d的值时,d.day的值会发生变化,结果会发生变化。< / p>

如果您希望获得第二个示例的结果,请将d.day替换为Date.today.day