2013-04-10 26 views
2

我一直對Enumerable#all?Enumerable#each的用例感到困惑。例如Enumerable#all的正確用例是什麼?和每個Ruby中的Enumerable#?

['.txt', '-hello.txt'].all? do |suffix| 
     puts "temp#{suffix}" 
     end 

作品對我來說,也

['.txt', '-hello.txt'].each do |suffix| 
     puts "temp#{suffix}" 
     end 

作品對我來說太。

我該選什麼.all?.each

+0

你確定兩者都產生相同的輸出嗎?我想不是。請重新驗證。 「每個人都沒有?」。 :( – 2013-04-10 07:32:05

回答

5

all?評估您傳遞給它的塊,如果所有元素均滿足,則返回true否則返回false

each是一種使用塊遍歷可枚舉對象的方法。它將評估每個對象的塊。在你的情況下,你想使用each

請參閱的文檔全部?here每個here

+0

同樣'任何?如果元素中有一個元素將塊評估爲「true」,則返回「true」。 – Candide 2013-04-10 07:24:23

+0

@Cideide是的,這是真的。但我不知道這個問題是否屬於這個問題的範圍。 :) – squiguy 2013-04-10 07:25:53

+0

謝謝...這真的有幫助 – 2013-04-10 10:06:39

1

見你的代碼和輸出:

['.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,因爲除nilfalse之外的所有對象都是true

相關問題