我希望每个数组元素都与其他数组元素交互。然而,我的代码中的某些元素具有意外的值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
。
1条答案
按热度按时间x8goxv8g1#
each
产生的是元素,而不是它们的索引,即n
变成了3
、4
、-7
、5
等。如果你好奇Ruby中数组索引是如何工作的,负索引从数组的末尾开始计数,
-1
是最后一个元素:如果你需要元素和它的索引,有
each_with_index
,它同时产生两个值:或者你可以使用
permutation
,它可以产生所有对:(同上)或者,如果将
a
与b
进行比较等同于将b
与a
进行比较(即,如果元素的顺序无关),则可能需要combination
,它省略了那些“重复”: