Ruby Array find_first object?

后端 未结 4 1071
既然无缘
既然无缘 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:53

    Do you need the object itself or do you just need to know if there is an object that satisfies. If the former then yes: use find:

    found_object = my_array.find { |e| e.satisfies_condition? }
    

    otherwise you can use any?

    found_it = my_array.any?  { |e| e.satisfies_condition? }
    

    The latter will bail with "true" when it finds one that satisfies the condition. The former will do the same, but return the object.

提交回复
热议问题