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]
这有什么错我的代码?
'如果ARG1 == x' - 一个数组永远不会等于它的一个元素,所以这个条件从来都不是真的。这就是为什么你没有指数。你是不是指'如果arg2 == x'? –
如果你的论点有更好的描述性名称,这个错误不会发生。 –
另外,'each_with_index'而不是'each'。 –