输入:[1,2,2,3,4,2]
输出:2 = [1,2,5]
的索引
答案 0 :(得分:3)
这样的方法:
def indexes_of_occurrence(ary, occ)
indexes = []
ary.each_with_index do |item, i|
if item == occ
indexes << i
end
end
return indexes
end
给您以下内容:
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)
=> []
我确信有一种方法可以做到一个班轮(似乎总是这样!)但是这样就可以了。
答案 1 :(得分:3)
一个好的,单行,干净的答案取决于您正在运行的Ruby版本。对于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
对于1.9:
foo = [1,2,2,3,4,2]
foo.collect.with_index {|x,i| i if x == 2}.compact
答案 2 :(得分:3)
轻松find_all
:
[1,2,2,3,4,2].each_with_index.find_all{|val, i| val == 2}.map(&:last) # => [1, 2, 5]
注意:如果使用Ruby 1.8.6,您可以require 'backports/1.8.7/enumerable/find_all'