arrays - 为什么我的枚举在 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]]
解决方案
您已尝试修改原始数组。那是你的问题。
在这种情况下,您需要像这样复制它:
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]]
推荐阅读
- c++ - 为什么不能使用'->' c++模板类
- google-chrome - 使用向页面注入脚本时访问 chrome 扩展中的全局变量
- android - 什么是 Android 进程“灰烬”以及如何防止它使我的应用程序休眠?(Android 7.0 打盹模式)
- python - 从 FTP 文件夹中读取 csv
- html - CSS问题页眉和页脚不保持高度
- r - r - 删除数据框中每个主题的第一行条件
- bash - 在bash脚本的变量中存储路径内的目录名称
- javascript - 动态添加工具提示
- sql - 来自 apache spark sql 的 ParseException 错误
- amazon-web-services - 附加/附加到传递给cloudformation的用户数据?