2015-04-14 131 views
2

我在Ruby中有一個包含一些重複元素的數組。例如: -獲取數組中重複元素的索引(Ruby)

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

當我執行以下操作:

fruits.index("apples") 
# returns 0 

我只能得到"apples"第一次出現是在這種情況下,fruits[0]。有沒有一種方法可以運行類似於上面的代碼並獲得"apples"其他事件的索引?如果我不能運行類似於上面的代碼的東西,我怎麼能得到重複元素的索引?

+0

@CarySwoveland對不起,我本來還打算;忘了。你的回答很有用。謝謝。 – GDP2

+0

我很高興聽到這是。 –

回答

3

以從程序語言的網頁,我們可以這樣寫:

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

不錯的單線。你能否在.select {| e,_ |中解釋「_」的用法... – grenierm5

+1

「_」只是表示變量不會被使用。 –

+0

請注意'_'確實是一個變量:'_ = 3;放置_#=> 3'。有些人喜歡寫一些像'| e,_ndx |'的東西。 –

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]} 
相關問題