-1

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?

5
  • 1
    What is the reason for down voting? Commented Jun 18, 2013 at 19:26
  • 1
    Because you could have found this by reading the docs, or via Google, I'd imagine. Commented Jun 18, 2013 at 20:49
  • 1
    I did read some doc on google. The scenario I am asking is a tricky one. Most of the examples online are without duplicated elements which is why I am posting my question here. Commented Jun 18, 2013 at 22:35
  • 1
    It's not tricky at all, index will find the first "b" without trouble: 'aabb'.index('b') => 2. Commented Jun 19, 2013 at 6:27
  • Sorry I still couldn't accept this question as a duplicate. Existing questions are always under the case WITHOUT duplicated elements. It is only not tricky if you already know the answer. Commented Aug 19, 2016 at 21:21

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

+1 I guess it's hard to beat that simplicity :)
@JoachimIsaksson could you look into my answer - stackoverflow.com/questions/17174644/…. I am thinking it can be made more simplistic,but I can't. so any help or advice from you.
Very interesting, I didn't know it will actually return the index of the first found element using .index(), most of the examples online are without duplicated elements. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.