The find_index method takes an enumerable collection and returns the index of first element for which the given block returns true. It works similar to the find/detect methods, but again it returns the *index* of the item in the collection, not the item itself.
- View the objects used in these examples
- View these examples as a runnable ruby script on GitHub.
- Practice this method as an interactive kata on Codewars!
Number List
@numbers = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8] # index of first even number: @numbers.find_index(&:even?) #=> 1 # index of first number divisible by three: @numbers.find_index{|number| number % 3 == 0} #=> 1
Pet Inventory
# index for scorpions: @inventory.find_index{|pet| pet.name == 'scorpion'} #=> 3 # index for first four-legged pet: @inventory.find_index{|pet| pet.legs == 4} #=> 0 # index for first pet with over 100 in stock: @inventory.find_index{|pet| pet.quantity > 100} #=> 2
Pokey Things
# index of first pokey thing with at least 3 letters: @pokey_things.seek(0) @pokey_things.map(&:chomp).find_index{|word| word.size >= 3} #=> 0 # index of first pokey thing with the letter 'e': @pokey_things.seek(0) @pokey_things.find_index{|line| line.include?('e')} #=> 1
Heroku Log File
# index of first heroku request made via the POST method: @requests.find_index(&:post?) #=> 21 # index of first heroku request with error: @requests.find_index{|request| request.error?} #=> 0