Ruby | Enumerable find_index() function

The find_index() of enumerable is an inbuilt method in Ruby returns the index of the item which returns true for the given condition in the block, or the index of the item which is equal to the given value. If no block is given, then it returns an enumerator. If the values is not present in the enumerable, then it returns nil.

Syntax: enu.find_index { |obj| block } or enu.find (val)

Parameters: The function takes a block whose condition is used to find the first element which is true or takes the value whose first occurrence is to be searched for.



Return Value: It returns the index.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program for find_index method in Enumerable
  
# Initialize 
enu = [8, 9, 10, 14]
  
# Prints
enu.find_index { |obj| obj % 2 == 1}

chevron_right


Output:

1

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Ruby program for find_index method in Enumerable
  
# Initialize 
enu = (1..6)
  
# Prints
puts enu.find_index(4)
  
puts enu.find_index(7)

chevron_right


Output:

3
nil


My Personal Notes arrow_drop_up

The function of education is to teach one to think intensively and to think critically

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.