Edward Edward - 1 year ago 103
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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download