获取数组中重复元素的索引 (Ruby)

Getting the indexes of duplicate elements in arrays (Ruby)

我在 Ruby 中有一个包含一些重复元素的数组。例如:

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

当我执行以下操作时:

fruits.index("apples")
# returns 0

我只得到第一次出现的 "apples",在本例中是 fruits[0]。有没有一种方法可以让我 运行 类似于上面的代码,并获得 "apples" 其他出现的索引?如果我不能 运行 类似于上面代码的东西,我还能如何获得重复元素的索引?

你可以这样做:

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

借鉴过程语言,我们可以这样写:

fruits.each_index.select { |i| fruits[i]=="apples" }
  #=> [0, 2, 4]