Dave
Dave

Reputation: 19150

How do I find the first elelment in my Ruby array matching certain criteria?

I’m using Rails 4.2.7. I want to find the first item in my array of objects whose fields match certain criteria. So I wrote this lengthy loop …

    result = nil
    results.each do |r|
      if r.valid?
        result = r 
        break
      end
    end

My question is, is there a shorter way to do this?

Upvotes: 1

Views: 78

Answers (2)

fbelanger
fbelanger

Reputation: 3568

Yup there is:

result = results.find(&:valid?)

https://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-find

Thanks to Rashmirathi for the ampersand + colon shortcut!

Upvotes: 0

Johny
Johny

Reputation: 1441

You can try to do that using Array method select

results = [{id: 1, valid: true}, {id: 2, valid: false}, {id:3, valid: true}]
result = results.select { |item|  item[:valid] == true}.first

You can find more at array documenation: https://ruby-doc.org/core-2.2.0/Array.html#method-i-select

Upvotes: 0

Related Questions