Ruby .detect array function

When i search items in an array in Ruby, I usually go with the select method, and get the first item it finds.

result = [3, 5, 1.3, ‘sample text’, nil, 7].select{|item| item.is_a?(Integer) }.first

The problem I have with using select is it always returns an array of all the items that satisfied the condition, so sometimes I encounter an error (nil.first error) if the result of the select function is null (and yes, not an empty array). That’s why I always add a line of code just to check if the result is null or not.

So one of my colleagues introduced me to the detect method of Array, which does the same thing as select, except that it returns only the first object that satisfies the condition. So the result is either the item or null.

result = [3, 5, 1.3, ‘sample text’, nil, 7].detect{|item| item.is_a?(Integer) }

Its pretty efficient.

Gotta refactor some select codes now. 🙂

1 comment

  1. Anonymous Reply
    November 30, -0001 at 12:00 am

    sa sunod ra nako na codes shii, ug kanang makit-an nako sa akong existing codes, ayha rako magrefactor 🙂

Leave A Comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked