Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Dates Calculation : Weird Outputs

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?

like image 775
Ankita Juhi Avatar asked Feb 05 '23 09:02

Ankita Juhi


2 Answers

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)
like image 61
Aleksei Matiushkin Avatar answered Feb 10 '23 04:02

Aleksei Matiushkin


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
like image 21
Stefan Avatar answered Feb 10 '23 06:02

Stefan