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:
I didn't find a great solution, but this will at least prevent walking the list twice:
Update: better solution was provided in the comments
Much better! (And I also just realized my previous solution wasn't gracefully handling the case where it wasn't found at all.)
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.)
https://github.com/kc0tlh/blackjack
How about:
a.find_index { |e| e.match( /ef/ ) }
?