1

Input : [1,2,2,3,4,2]

Output : Index of 2 = [1,2,5]

3 Answers 3

3

A method like this:

def indexes_of_occurrence(ary, occ)
  indexes = []
  ary.each_with_index do |item, i|
    if item == occ
      indexes << i
    end
  end
  return indexes
end

Gives you the following:

irb(main):048:0> indexes_for_occurrence(a, 2)
=> [1, 2, 5]
irb(main):049:0> indexes_for_occurrence(a, 1)
=> [0]
irb(main):050:0> indexes_for_occurrence(a, 7)
=> []

I'm sure there's a way to do it a one liner (there always seems to be!) but this'll do the job.

Sign up to request clarification or add additional context in comments.

Comments

3

A nice, single line, clean answer depends on what version of Ruby you are running. For 1.8:

require 'enumerator'
foo = [1,2,2,3,4,2]
foo.to_enum(:each_with_index).collect{|x,i| i if x == 2 }.compact

For 1.9:

foo = [1,2,2,3,4,2]
foo.collect.with_index {|x,i| i if x == 2}.compact

2 Comments

You can do .compact instead of .reject { |x| x.nil? } which would make it shorter.
Good catch. I edited to reflect your suggestion, thanks Shadwell :)
3

Easy with find_all:

[1,2,2,3,4,2].each_with_index.find_all{|val, i| val == 2}.map(&:last) # => [1, 2, 5]

Note: If using Ruby 1.8.6, you can require 'backports/1.8.7/enumerable/find_all'

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.