2010-06-07 179 views
29

選擇是有道理的。但有人可以解釋一下,檢測到我嗎?我不明白這些數據。紅寶石檢測方法

>> [1,2,3,4,5,6,7].detect { |x| x.between?(3,4) } 
=> 3 
>> [1,2,3,4,5,6,7].detect { |x| x.between?(3,6) } 
=> 3 
>> [1,2,3,4,5,6,7].detect { |x| x.between?(3,7) } 
=> 3 
>> [1,2,3,4,5,6,7].detect { |x| x.between?(2,7) } 
=> 2 
>> [1,2,3,4,5,6,7].detect { |x| x.between?(1,7) } 
=> 1 
>> [1,2,3,4,5,6,7].detect { |x| x.between?(6,7) } 
=> 6 
>> [1,2,3,4,5,6,7].select { |x| x.between?(6,7) } 
=> [6, 7] 
>> [1,2,3,4,5,6,7].select { |x| x.between?(1,7) } 
=> [1, 2, 3, 4, 5, 6, 7] 

回答

65

Detect返回列表中返回TRUE的第一個項目。您的第一個例子:

>> [1,2,3,4,5,6,7].detect { |x| x.between?(3,4) } 
=> 3 

返回3,因爲這是在爲表達x.between?(3,4)返回TRUE列表中的第一項。

detect在條件第一次返回true時停止迭代。將會迭代select,直到達到輸入列表的末尾並返回塊返回true的所有項目。

+2

強制性RubyDoc鏈接:http://ruby-doc.org/ core/classes/Enumerable.html#M003123 – 2010-06-07 03:02:29

+14

'detect'的別名是'find'。對我來說,如果我把它看作「發現」,就更容易理解該方法的語義。 – Florin 2012-10-09 08:36:49

+2

然而,使用「檢測」和「查找」可互換似乎並不正確。如果你檢查ruby文檔,如果它在檢測和查找示例代碼中指出它們的行爲不同,事實上很難弄清楚「發現」和「檢測」之間的區別,因爲兩種方法的解釋性文本都是完全相同的,但解釋方法不同。 http://ruby-doc.org/core-2.2.1/Enumerable.html#method-i-find – 2015-04-08 13:40:09

9

detect只返回滿足謂詞的第一個值,否則爲零。 select返回所有滿足謂詞的值。 a.detect { p }類似於a.select { p }[0]

irb(main):001:0> [1,2,3].detect { true } 
=> 1 
irb(main):002:0> [1,2,3].detect { false } 
=> nil 
irb(main):003:0> [1,2,3].detect { |x| x % 2 == 0 } 
=> 2 
1

找到&檢測總是要麼返回一個對象或他們將返回nil,如果沒有匹配。

例如[1,2,3,4,5,6,7] .detect {| x | x.between?(1,7)} => 1

find_all並且select將返回一個它發現匹配的數組。

例如[1,2,3,4,5,6,7] .select {| x | ?x.between(1,7)} => [1,2,3,4,5,6,7]

Reference Link