Reputation: 443
Input : [1,2,2,3,4,2]
Output : Index of 2 = [1,2,5]
Upvotes: 1
Views: 170
Reputation: 79582
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'
Upvotes: 3
Reputation: 3259
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
Upvotes: 3
Reputation: 34774
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.
Upvotes: 3