Ruby 嵌套 .each 块中的某些数组元素变为 nil

Ruby some array elements in nested .each block become nil

提问人:poeticider 提问时间:4/19/2023 最后编辑:Stefanpoeticider 更新时间:4/20/2023 访问量:62

问:

我希望每个数组元素相互交互。但是,我的代码中的某些元素具有意外的值。nil

如何避免这种不良行为?

下面是组合元素的代码:(它只是打印成对)

def remove_sum_of_zero(arr)
  arr.each do |n|
    arr.each do |x|
      unless arr.index(n) == arr.index(x)
        puts "#{arr[n]} is being checked with #{arr[x]}"
      end
    end
  end
end

numArr = [3, 4, -7, 5, -6, 6]
remove_sum_of_zero(numArr)

输出:

5 is being checked with -6
5 is being checked with
5 is being checked with 6
5 is being checked with 3
5 is being checked with
-6 is being checked with 5
-6 is being checked with
-6 is being checked with 6
-6 is being checked with 3
-6 is being checked with
is being checked with 5
is being checked with -6
is being checked with 6
is being checked with 3
is being checked with
6 is being checked with 5
6 is being checked with -6
6 is being checked with
6 is being checked with 3
6 is being checked with
3 is being checked with 5
3 is being checked with -6
3 is being checked with
3 is being checked with 6
3 is being checked with
is being checked with 5
is being checked with -6
is being checked with
is being checked with 6
is being checked with 3

我尝试使用不同的数组,每次不同的值变成.nil

数组 Ruby

评论

0赞 Stefan 4/19/2023
如果您打算实际删除零和对,请记住,在遍历数组时不应对其进行更改。

答:

4赞 Stefan 4/19/2023 #1

each产生元素,而不是它们的索引,即 变为 、 、 等。将该值作为索引传递没有多大意义。n34-75arr[n]

如果你好奇数组索引在 Ruby 中是如何工作的——负索引从数组的末尾算作最后一个元素:-1

numArr = [ 3,  4, -7,  5, -6,  6]
#          0   1   2   3   4   5   6 ... ← positive indices (and 0)
# ... -7  -6  -5  -4  -3  -2  -1         ← negative indices

如果你需要元素及其索引,each_with_index可以同时生成两个值:

def remove_sum_of_zero(arr)
  arr.each_with_index do |a, i|
    arr.each_with_index do |b, j|
      next if i == j

      puts "#{a} is being checked with #{b}"
    end
  end
end

或者您可以使用可以产生所有对的排列:(即与上述相同)

def remove_sum_of_zero(arr)
  arr.permutation(2) do |a, b|
    puts "#{a} is being checked with #{b}"
  end
end

或者,如果 compare to 等同于 compare to(即,如果元素的顺序无关紧要),您可能需要省略这些“重复项”的组合abba

def remove_sum_of_zero(arr)
  arr.combination(2) do |a, b|
    puts "#{a} is being checked with #{b}"
  end
end