【问题标题】:Why is my enumeration stopping after first rejection in Ruby?为什么我的枚举在 Ruby 中第一次被拒绝后停止?
【发布时间】:2019-09-18 21:28:27
【问题描述】:

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

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】:

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

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

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

    【讨论】:

    • 嗯...我理解您关于影响来源和需要副本的逻辑。但是我无法得到您的建议来处理我的示例数据,例如[[0, 1], [2, 3], [0, 5]],这产生了arr =&gt; [] - 我会接受答案,因为它似乎在某些情况下有效 - 我想我会选择 if/ elsif 条件来代替填充新数组
    • @brian-welch,我已经更新了答案。希望这会有所帮助
    猜你喜欢
    • 2022-07-15
    • 2019-01-31
    • 2019-01-10
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    • 2021-01-01
    • 2016-11-01
    相关资源
    最近更新 更多