Dave Dave - 1 year ago 66
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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download