Experiences on the Front Lines of User Interfaces and Web Development

Ruby method to find index of first matching element

I wanted to find the index of the first element in the array that matched a certain regex pattern.  There were a handful of methods that would give me back the array element, but doing that then finding the index of that element seemed lame and inefficient:
a = [ "abc", "def", "ghi" ]
a.index( a.detect{ |e| e.match( /ef/ ) } )

I didn't find a great solution, but this will at least prevent walking the list twice:
a.enum_with_index.find{ |e, i| e.match( /ef/ ) }.last

Update: better solution was provided in the comments
a.find_index { |e| e.match( /ef/ ) }

Much better! (And I also just realized my previous solution wasn't gracefully handling the case where it wasn't found at all.)


Just used this in my blackjack game:

This comment has been removed by the author.
Colin, that works great.. thanks for the tip! I knew there was a succinct Ruby way to do it.
Colin Kelley
Hey Nick,

How about:

a.find_index { |e| e.match( /ef/ ) }


comments powered by Disqus