Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

Ruby Detect method

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]
question from:https://stackoverflow.com/questions/2986852/ruby-detect-method

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...