2013-03-29 55 views
0

enum#detect說:混亂與枚舉#`檢測輸出nil`

通行證枚舉阻止每個條目。返回第一個塊不是假的。如果沒有對象匹配,則調用ifnone並在指定時返回結果,否則返回nil。

現在我試圖在下面:

nil.call 
#NoMethodError: undefined method `call' for nil:NilClass 
#  from (irb):13 
#  from C:/Ruby200/bin/irb:12:in `<main>' 


(1..10).detect(x = 2) { |i| i % 5 == 0 and i % 7 == 0 } 
#NoMethodError: undefined method `call' for 2:Fixnum 
#  from (irb):15:in `detect' 
#  from (irb):15 
     from C:/Ruby200/bin/irb:12:in `<main>' 

現在是,爲什麼沒有發生在我下面的問題,同樣的錯誤:

(1..10).detect(x = nil) { |i| i % 5 == 0 and i % 7 == 0 } 
#=> nil 
(1..10).detect(x = nil) { |i| p x; i % 5 == 0 and i % 7 == 0 } 
#nil 
#nil 
#nil 
#nil 
#nil 
#nil 
#nil 
#nil 
#nil 
#nil 
#=> nil 

回答

1

如果你看的源代碼detect方法(點擊文檔頁面上的'查看源代碼'),你會發現它只會嘗試執行call,如果參數是而不是nil

if (!NIL_P(if_none)) { 
    return rb_funcall(if_none, id_call, 0, 0); 
} 
+0

是的!你是對的,我沒有看到那個源代碼,因爲有時候這些'C'代碼沒有被我理解。 :( –

+0

你可以加入這裏 - http://chat.stackoverflow.com/rooms/27184/ruby-conceptual? –

0

如果沒有對象匹配,調用ifnone並指定時返回其結果,或否則返回零。

我認爲你解析這個句子的方式不同於它的意圖。什麼這裏所指的是:

if no object matches 
    if ifnone is set 
    return ifnone.call 
    else 
    return nil 
    end 
end 

如果您在nil作爲參數傳遞,則計爲ifnone沒有被設置,所以它不叫。只有在您傳遞的值不是nil時纔會調用它。

+0

我設置'x = nil',那麼怎麼樣?如果你看到最後的代碼輸出,所有' nil'輸出作爲輸出,這意味着'x'設置爲'nil' –

+0

@iAmRubuuu是的,'x'設置爲'nil',因爲你設置爲'nil'。我不太瞭解你的問題。請注意,'foo(x = bar)'與'x = bar; foo(x)'相同。 – sepp2k

+0

humm我從另一個答案中得到了答案。我的意思是說'nil.call'不被支持,最後一個代碼成功了嗎? –