I have observed that a ruby expression calculating days difference gives different output dependent on the spaces in the expression.
Date.today #=> #<Date: 2017-01-06 ((2457760j,0s,0n),+0s,2299161j)>
(Date.today - 60).to_s #=> "2016-11-07"
(Date.today-60).to_s #=> "2016-11-07"
(Date.today- 60).to_s #=> "2016-11-07"
(Date.today -60).to_s #=> "2017-01-06" <- ???
Can anybody help me understand the reason behind it?
That is the matter of operator precedence. Date::today
accepts an optional argument.
Date.today - 60
is treated as
Date.today() - 60
while
(Date.today -60)
is treated as
Date.today(-60)
In addition to mudasobwa's spot-on answer: you should turn warnings on while developing.
Without -w
:
$ ruby -rdate -e 'puts Date.today -60'
2017-01-06
With -w
:
$ ruby -w -rdate -e 'puts Date.today -60'
-e:1: warning: ambiguous first argument; put parentheses or a space even after `-' operator
-e:1: warning: invalid start is ignored
2017-01-06
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With