2017-01-06 54 views
3

我观察到,计算天差异的ruby表达式会根据表达式中的空间给出不同的输出。红宝石日期计算:奇怪的输出

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" <- ??? 

有人能帮我理解背后的原因吗?

+3

_Sidenote:_似乎是接受记者采访时一个很好的问题。 – mudasobwa

回答

7

这是运算符优先级的问题。 Date::today接受可选参数。

Date.today - 60 

被视为

Date.today() - 60 

(Date.today -60) 

被视为

Date.today(-60) 
2

除了mudasobwa现货上answer:你应该打开,同时警告DEVE loping。

没有-w

$ ruby -rdate -e 'puts Date.today -60' 
2017-01-06 

随着-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