2017-01-06 55 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