Dave Dave - 18 days ago 5
Ruby Question

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?

Answer

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!

Comments