为什么我的枚举在Ruby中首次被拒绝后停止了?

问题描述 投票:0回答:1

迫切需要帮助。我试图从数组和数组中删除数组,我遇到了障碍。实质上,如果子数组中的第一个值不存在于任何其他子数组的任一位置,则应删除它。 (假设数组将被排序 - 因为它将是)

arr = [[0, 1], [2, 3], [4, 5]]
arr.each_with_index do |inside_array, index|
    if !index.zero?
        # arr.delete(arr[index]) if arr.select {|x| x.include?(inside_array[0])}.count < 2
        # refactored
        arr.reject! {|x| x.include?(inside_array[0])}
    end
end
=> [[0, 1], [4, 5]]
# Why does it stop itterating/enumerating after the first deletion?
# Goal output is [[0, 1]] for this example

类似地,像[[0, 1], [2, 3], [1, 5]]这样的数组应该产生[[0, 1], [1, 5]] - 或 - [[0, 1], [2, 3], [0, 3]],应该产生[[0, 1], [0, 3]]

arrays ruby methods enumeration
1个回答
0
投票

您已尝试修改原点数组。那是你的问题。

在这种情况下,您需要像这样复制它:

arr = [[0, 1], [2, 3], [4, 5]]
arr.dup.each_with_index do |inside_array, index|
  if !index.zero?
    arr.reject! {|x| x.include?(inside_array[0])}
  end
end

arr #=> [[0, 1]]

所以只需使用dup

至于第二个问题(子阵列删除的实现),我建议这个重构:

def remove_subarray(arr)
  arr.reject { |inside_array| (inside_array & arr.first).empty? }
end

remove_subarray([[0, 1], [2, 3], [4, 5]]) #=> [[0, 1]]
remove_subarray([[0, 1], [2, 3], [1, 5]]) #=> [[0, 1], [1, 5]]
remove_subarray([[0, 1], [2, 3], [0, 3]]) #=> [[0, 1], [0, 3]]
© www.soinside.com 2019 - 2024. All rights reserved.