find the index of an element in an array in ruby

To find the index of an element in an array in Ruby, you can use the Array#index method. Here's an example:

main.rb
array = [5, 10, 15, 20, 25]
element = 15

index = array.index(element)

puts index  # Output: 2
96 chars
7 lines

In the example above, we first create an array of integers, and then we define the element variable to store the value we're looking to find the index of. We then call the index method on the array object and pass our element variable as an argument. The index method then returns the index of the first occurrence of the element in the array.

If the element is not found in the array, the index method will return nil.

related categories

gistlibby LogSnag