This is not a problem so much as something I noticed and was wondering if someone could explain it to me.
If I use inline-type syntax I get two different, interchanging, answers:
d = (Date.today >> 3) - (d.day + 1)
#=> #<Date: 2013-06-01 ((2456445j,0s,0n),+0s,2299161j)>
d = (Date.today >> 3) - (d.day + 1)
#=> #<Date: 2013-06-03 ((2456447j,0s,0n),+0s,2299161j)>
d = (Date.today >> 3) - (d.day + 1)
#=> #<Date: 2013-06-01 ((2456445j,0s,0n),+0s,2299161j)>
d = (Date.today >> 3) - (d.day + 1)
#=> #<Date: 2013-06-03 ((2456447j,0s,0n),+0s,2299161j)>
If I do the same on multiple lines I get the same correct answer every time:
d = Date.today
#=> #<Date: 2013-03-05 ((2456357j,0s,0n),+0s,2299161j)>
d = d >> 3
#=> #<Date: 2013-06-05 ((2456449j,0s,0n),+0s,2299161j)>
d = d - d.day + 1
#=> #<Date: 2013-06-01 ((2456445j,0s,0n),+0s,2299161j)>
d = Date.today
#=> #<Date: 2013-03-05 ((2456357j,0s,0n),+0s,2299161j)>
d = d >> 3
#=> #<Date: 2013-06-05 ((2456449j,0s,0n),+0s,2299161j)>
d = d - d.day + 1
#=> #<Date: 2013-06-01 ((2456445j,0s,0n),+0s,2299161j)>
Any ideas why this would happen? I am just interested to understand because, the way I see it, both ways should always return the same answer.
This has nothing to do with Ruby's date format.
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