Dave Dave - 9 months ago 36
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

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

Answer Source

Yup there is:

result = results.find(&:valid?)


Thanks to Rashmirathi for the ampersand + colon shortcut!