Ruby Detect method

前端 未结 4 1101
情书的邮戳
情书的邮戳 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:32

    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
    

提交回复
热议问题