How to Find Array Index in Ruby
Sometimes we need to find the index of a specific element of an array. You may create loops to go through the elements of an array individually and collect the index when the searched element is found.
But if you are working with Ruby, it’s very easy to find an index of an element.
This article will discuss finding the index of a specific array element in Ruby. Also, we will look at an example to make the topic easier.
Find the Index of an Array Element in Ruby
A built-in function in Ruby allows you to get the index of a specific array element. In the below example, we will illustrate how we can find the index of a specific array element with a single line of code.
Look at the below example code.
arr = %w[a b c]
puts arr.find_index('c')
In the example above, we will find the index of array element c
from the array arr
. After running the example above, you will get the below output.
2
Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.
LinkedIn