【问题标题】:How to find all indices of a given element in an array?如何查找数组中给定元素的所有索引?
【发布时间】:2018-01-11 23:13:59
【问题描述】:

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

我的代码有什么问题?

【问题讨论】:

  • if arg1 == x - 一个数组永远不会等于它的一个元素,所以这个条件永远不会成立。这就是为什么你没有索引。你的意思是if arg2 == x
  • 如果您的参数有更好、更具描述性的名称,就不会发生此错误。
  • 另外,each_with_index 而不是 each
  • 根据 Sergio 的评论:each 只能访问值,而不是索引,因此 y 将始终为 nileach_with_index 将为您提供值和索引(按此顺序)。

标签: ruby


【解决方案1】:

其他一些给猫剥皮的方法。

遍历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

【讨论】:

    【解决方案2】:
    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]
    

    【讨论】:

      猜你喜欢
      • 2019-07-12
      • 2014-01-14
      • 2018-09-25
      • 1970-01-01
      • 2016-06-09
      • 1970-01-01
      • 2019-06-23
      • 2020-06-01
      • 2011-09-04
      相关资源
      最近更新 更多