首页 > 解决方案 > 为什么我的枚举在 Ruby 中第一次被拒绝后停止?

问题描述

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

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]]

标签: arraysrubymethodsenumeration

解决方案


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

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

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]]

推荐阅读