6

I have an array in Ruby that has some duplicate elements. E.g.:

fruits = ["apples", "bananas", "apples", "grapes", "apples"]

When I do the following:

fruits.index("apples")
# returns 0

I only get the first occurrence of "apples" which is, in this case, fruits[0]. Is there a way that I can run something similar to the above code and get the indexes of the other occurrences of "apples"? If I can't run something similar to the above code, how else can I get the indexes of the duplicate elements?

2
  • @CarySwoveland Sorry, I had meant to; simply forgot. Your answer was useful; thanks. Commented Sep 26, 2016 at 15:35
  • I'm glad to hear it was. Commented Sep 26, 2016 at 16:13

3 Answers 3

11

Taking a page from procedural languages, we could write:

fruits.each_index.select { |i| fruits[i]=="apples" }
  #=> [0, 2, 4]
Sign up to request clarification or add additional context in comments.

Comments

3

You can do this:

fruits.to_enum.with_index.select{|e, _| e == "apples"}.map(&:last)
# => [0, 2, 4]

2 Comments

The "_" just means the variable is not going to be used.
Note that _ is indeed a variable: _=3; puts _#=> 3. Some prefer writing something like |e,_ndx|.
0
fruits = ["apples", "bananas", "apples", "grapes", "apples"]

p fruits.each_with_index.group_by{|f,i| f}.each{|k,v| v.map!(&:last)}
# => {"apples"=>[0, 2, 4], "bananas"=>[1], "grapes"=>[3]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.