通行證枚舉阻止每個條目。返回第一個塊不是假的。如果沒有對象匹配,則調用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
是的!你是對的,我沒有看到那個源代碼,因爲有時候這些'C'代碼沒有被我理解。 :( –
你可以加入這裏 - http://chat.stackoverflow.com/rooms/27184/ruby-conceptual? –