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

6

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

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

当我执行以下操作时:
fruits.index("apples")
# returns 0

我只得到了第一次出现的"apples",也就是在此情况下fruits[0]。有没有一种方法可以运行类似上面代码的东西,并获取其他"apples"出现的索引?如果不能运行类似于上面的代码,那么我该如何获取重复元素的索引?


@CarySwoveland 对不起,我本来想的;只是忘了。你的答案很有用;谢谢。 - GDP2
很高兴听到这个消息。 - Cary Swoveland
3个回答

11

借鉴过程式语言的做法,我们可以这样写:

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

3
你可以这样做:
fruits.to_enum.with_index.select{|e, _| e == "apples"}.map(&:last)
# => [0, 2, 4]

1
"_" 只是表示该变量不会被使用。 - Tucker
请注意,下划线 _ 确实是一个变量:_=3; puts _#=> 3。有些人喜欢编写类似 |e,_ndx| 的代码。 - Cary Swoveland

0
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]}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接