2012-01-19 37 views
17

想象一下這是1月19日。如果你今天看到這個問題,這並不難。Ruby表達式評估:空白是否重要?

Date.today 
=> Thu, 19 Jan 2012 # as expected 

Date.today + 1 
=> Fri, 20 Jan 2012 # as expected 

Date.today+1 
=> Fri, 20 Jan 2012 # as expected 

Date.today +1 
=> Thu, 19 Jan 2012 # ?! 

我在這裏錯過了什麼?

+4

這很有趣:-) –

回答

16

不同之處在於:

Date.today + 1 

是兩個數值的加和

Date.today +1 

被該方法today一個呼叫與所述參數sg(日曆改革天)與值+1

檢查此問題的最佳方法是將調試輸出的原始方法cluded。看到這個腳本例子:

require 'date' 

class Date 

    def self.today(sg=ITALY) 
    puts "ITALY default("+sg.to_s+")" if sg==ITALY 
    puts sg unless sg==ITALY 
    jd = civil_to_jd(*(Time.now.to_a[3..5].reverse << sg)) 
    new0(jd_to_ajd(jd, 0, 0), 0, sg) 
    end 

end 

puts "- Addition:" 
Date.today + 1 
puts "- Parameter:" 
Date.today +1 

這將打印以下控制檯輸出:

- Addition: 
ITALY default(2299161) 
- Parameter: 
1 
4

是,空白確實在Ruby中事情,出乎人們意料。例如,foo barfoobar不一樣。

在此特定情況下,

Date.today + 1 

相同

Date.today().+(1) 

鑑於

Date.today +1 

相同

Date.today(+1) 

這與

相同
Date.today([email protected]())