Ruby Detect method

大城市里の小女人 提交于 2019-12-31 08:35:32

问题


Select makes sense. But can someone explain .detect to me? I don't understand these data.

>> [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]

回答1:


Detect returns the first item in the list for which the block returns TRUE. Your first example:

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

Returns 3 because that is the first item in the list that returns TRUE for the expression x.between?(3,4).

detect stops iterating after the condition returns true for the first time. select will iterate until the end of the input list is reached and returns all of the items where the block returned true.




回答2:


detect just returns the first value that satisfies the predicate, if any, nil otherwise. select returns all the values that satisfy the predicate. a.detect { p } is analogous to 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



回答3:


The ruby-docs are a great ressource when you want to learn about the methods.

Enumerable#detect




回答4:


find and detect will always either return a single object or they will return nil if nothing is matched:

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

find_all and select will return an array of things that it finds that match:

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

Reference Link



来源:https://stackoverflow.com/questions/2986852/ruby-detect-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!