我正在尝试使用一种方法对 Array 类进行修补,当传递类似 时[1, 3, 4, 3, 0, 3, 1],将返回带有 的哈希{ 1 => [0, 6], 3 => [1, 3, 5] },其中键是我们匹配的数字,值是具有所有匹配项索引的数组。
这是我到目前为止的代码。我不知道为什么它会返回类似的东西{1=>[0, 2, 3, 1, 2, 0], 3=>[0, 2, 3, 1, 2, 0], 0=>[0, 2, 3, 1, 2, 0]}:
class Array
  def dups
    matches = {}
    matches_index = []
    self.each do |i|
      self[(i_index + 1)..-1].each_with_index do |j, j_index|
        matches_index << j_index if self[i] == self[j]
      end
      matches[i] = matches_index
    end
    matches.keep_if { |key, value| value.length > 1 }
  end
end