tags:

views:

69

answers:

3

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

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

+3  A: 

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.

Shadwell
+3  A: 

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
animal
You can do .compact instead of .reject { |x| x.nil? } which would make it shorter.
Shadwell
Good catch. I edited to reflect your suggestion, thanks Shadwell :)
animal
+3  A: 

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, require 'backports'

Marc-André Lafortune