Edward Edward - 3 months ago 9
Ruby Question

Finding the index of a particular element in an array with duplicated elements

Let's say I have the following array:

array = ["a","a","a","a","a","a","b","b","b","b","b","b"]


I want to find the index of the first "b" in the array. What is the best way of doing it?

Answer

Use Array#index for first occurrence and Array#rindex for last occurrence of an element.

array = ["a","a","a","a","a","a","b","b","b","b","b","b"]
array.index("b") # => 6
array.rindex("b") # => 11