Ruby Array find_first object?

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

    Guess you just missed the find method in the docs:

    my_array.find {|e| e.satisfies_condition? }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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]
    
    0 讨论(0)
  • 2020-12-25 10:02

    Either I don't understand your question, or Enumerable#find is the thing you were looking for.

    0 讨论(0)
提交回复
热议问题