見你的代碼和輸出:
['.txt', '-hello.txt'].all? do |suffix|
puts "temp#{suffix}"
end
p "======================="
['.txt', '-hello.txt'].each do |suffix|
puts "temp#{suffix}"
end
輸出:
temp.txt
"======================="
temp.txt
temp-hello.txt
但現在的問題是,爲什麼從第一代碼 'TEMP.TXT'?。是的puts
返回nil
。見下文現在:
['.txt', '-hello.txt'].all? do |suffix|
p "temp#{suffix}"
end
p "======================="
['.txt', '-hello.txt'].each do |suffix|
puts "temp#{suffix}"
end
輸出:
"temp.txt"
"temp-hello.txt"
"======================="
temp.txt
temp-hello.txt
說明:
Enum#all?
說:
傳遞到給定塊集合中的每個元素。該方法返回true如果該塊永不返回false或零。
將第一個元素傳遞給塊後,您的第一個代碼puts
返回nil
。只有當每個項目評估爲true
時,傳遞至all?
的塊纔會繼續。因此塊返回"temp.txt"
。第二個版本不是這種情況。由於p
永遠不會返回nil
。因此,該塊評估爲true
,因爲除nil
和false
之外的所有對象都是true
。
你確定兩者都產生相同的輸出嗎?我想不是。請重新驗證。 「每個人都沒有?」。 :( – 2013-04-10 07:32:05