0

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

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

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)>

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

4

2 回答 2

2

这与 Ruby 的日期格式无关。

It is to do with when d is evaluated in each expression on the right hand side. Namely, at the start of the statement evaluation, and not again during it:

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

d = 1
d = 1 + d
d = d + d
=> 4
于 2013-03-05T15:06:10.967 回答
1

d.day指的是 的现有值d,因此当您更改 的值时d,结果的值也会随之d.day变化。

如果要实现第二个示例的结果,请替换d.dayDate.today.day.

于 2013-03-05T15:02:17.290 回答