2016-09-22 113 views
9

雖然在http://guides.rubyonrails.org/layouts_and_rendering.html#avoiding-double-render-errors經歷了Rails指南, 我寫了一個測試程序來測試Ruby的&& return,我得到這個奇怪的現象:紅寶石:「&&返回」 VS「並返回」

def test1 
    puts 'hello' && return 
    puts 'world' 
end 

def test2 
    puts 'hello' and return 
    puts 'world' 
end 

這是結果輸出:

irb(main):028:0> test1 
=> nil 
irb(main):029:0> test2 
hello 
world 
=> nil 

什麼說明了區別?

+0

關於此問題的良好討論:https://www.ruby-forum.com/topic/217700 – Yarin

回答

16

結帳the difference between and and &&。在示例中,您給出的方法puts被稱爲沒有parens的參數,優先級的差異會改變它的解析方式。

測試1中&&比方法調用具有更高的優先級。所以實際發生的是puts('hello' && return)。參數總是在它們被調用的方法之前被評估 - 所以我們首先評估'hello' && return。由於'hello'是真實的布爾不會短路和return評估。當返回時,我們退出該方法而不做其他任何事情:因此沒有記錄任何內容,並且第二行不運行。

測試2中and的優先級低於方法調用。那麼會發生什麼是puts('hello') and return。方法puts記錄傳遞給它的內容,然後返回nilnil是錯誤的值,因此and表達式短路和return表達式從不被評估。我們只是轉到puts 'world'運行的第二行。

+0

謝謝!我注意到了什麼問題~~但我無法看到「&&比方法調用有更高的優先級」。存在於http://phrogz.net/ProgrammingRuby/language.html#table_18.4中,我無法證明它... – Spec