ruby中嵌套的一些数组元素,每个块都变成nil

dy1byipe  于 2023-04-20  发布在  Ruby
关注(0)|答案(1)|浏览(130)

我希望每个数组元素都与其他数组元素交互。然而,我的代码中的某些元素具有意外的值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

x8goxv8g

x8goxv8g1#

each产生的是元素,而不是它们的索引,即n变成了34-75等。
如果你好奇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

或者你可以使用permutation,它可以产生所有对:(同上)

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

或者,如果将ab进行比较等同于将ba进行比较(即,如果元素的顺序无关),则可能需要combination,它省略了那些“重复”:

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

相关问题