Ruby Array find_first object?

后端 未结 4 1073
既然无缘
既然无缘 2020-12-25 09:15

Am I missing something in the Array documentation? I have an array which contains up to one object satisfying a certain criterion. I\'d like to efficiently find that objec

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-25 09:57

    use array detect method if you wanted to return first value where block returns true

    [1,2,3,11,34].detect(&:even?) #=> 2
    
    OR
    
    [1,2,3,11,34].detect{|i| i.even?} #=> 2
    

    If you wanted to return all values where block returns true then use select

    [1,2,3,11,34].select(&:even?)  #=> [2, 34]
    

提交回复
热议问题