2017-08-04 103 views
0

此代碼應該詞'hello'的索引添加到indices陣列,但它不是將它們添加到陣列:如何查找數組中給定元素的所有索引?

words = %w(hello how are you then okay then hello how) 

def global(arg1, arg2) 
    indices = [] 
    arg1.each do |x, y| 
    indices << y if arg2 == x 
    end 
    indices 
end 

global(words,'hello') 
#=> [nil, nil] 

這有什麼錯我的代碼?

+1

'如果ARG1 == x' - 一個數組永遠不會等於它的一個元素,所以這個條件從來都不是真的。這就是爲什麼你沒有指數。你是不是指'如果arg2 == x'? –

+4

如果你的論點有更好的描述性名稱,這個錯誤不會發生。 –

+3

另外,'each_with_index'而不是'each'。 –

回答

4

一些其他的方法來剝皮貓。

導線​​和select其元素的那些搜索詞相匹配:

def indices(words, searched_word) 
    words.each_index.select { |index| words[index] == searched_word } 
end 

遍歷每個字與它的索引(each_with_index)沿和索引存儲在一個明確的indices陣列如果字相匹配。然後返回indices陣列:

def indices(words, searched_word) 
    indices = [] 
    words.each_with_index do |word, index| 
    indices << index if word == searched_word 
    end 
    indices 
end 

與上述相同,但通過with_object明確數組傳遞對進入迭代(這也將返回陣列):

def indices(words, searched_word) 
    words.each_with_index.with_object([]) do |(word, index), indices| 
    indices << index if word == searched_word 
    end 
end 
1
def indices(words, searched_word) 
    words.each_with_index.select { |word, _| word == searched_word }.map(&:last) 
end 

words = %w(hello how are you then okay then hello how) 

indices words, 'hello' # => [0, 7] 
相關問題