Ruby Detect method

前端 未结 4 1040
情书的邮戳
情书的邮戳 2021-01-31 03:00

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
>&g         


        
4条回答
  •  星月不相逢
    2021-01-31 03:13

    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.

提交回复
热议问题