To get the index of a specified element in an array in Ruby, you can use the index method or find_index method.
In this example,
arr
with values 10, 20, 30, 40, 50.index
method to find the index of element 30 in the array.index
method returns the index of the first occurrence of the element, or nil if the element is not found.arr = [10, 20, 30, 40, 50]
index = arr.index(30)
puts "Index of element 30 is: #{index}"
Index of element 30 is: 2
In this example,
arr
with values 10, 20, 30, 40, 50.find_index
method to find the index of element 60 in the array.find_index
method returns the index of the first occurrence of the element, or nil if the element is not found.arr = [10, 20, 30, 40, 50]
index = arr.find_index(60)
puts "Index of element 60 is: #{index || 'Element not found'}"
Index of element 60 is: Element not found
In this tutorial, we learned How to get the Index of Specified Element in an Array in Ruby language with well detailed examples.