如何查找数组中给定元素的所有索引?

时间:2017-08-04 06:27:11

标签: ruby

此代码应该将单词'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]

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:4)

其他一些皮肤猫的方法。

遍历each_indexselect其元素与搜索到的字匹配的内容:

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 :(得分: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]