2017-08-04 104 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] 
相关问题