ruby - 在 Ruby 中迭代时删除?

标签 ruby loops

我正在遍历一组非常大的字符串,而这些字符串又遍历了一组较小的字符串。由于大小,此方法需要一段时间才能完成,因此为了加快速度,我试图从较小的集合中删除不再需要使用的字符串。以下是我当前的代码:

    Ms::Fasta.foreach(@database) do |entry|
        all.each do |set|
            if entry.header[1..40].include? set[1] + "|"
                startVal = entry.sequence.scan_i(set[0])[0]

                if startVal != nil
                    @locations << [set[0], set[1], startVal, startVal + set[1].length]
                    all.delete(set)
                end
            end
        end
    end

我面临的问题是,简单的方法 array.delete(string) 有效地向内部循环添加了一个 break 语句,这弄乱了结果。我知道如何解决这个问题的唯一方法是这样做:

Ms::Fasta.foreach(@database) do |entry|
        i = 0

        while i < all.length
            set = all[i]

            if entry.header[1..40].include? set[1] + "|"
                startVal = entry.sequence.scan_i(set[0])[0]

                if startVal != nil
                    @locations << [set[0], set[1], startVal, startVal + set[1].length]
                    all.delete_at(i)
                    i -= 1
                end
            end

            i += 1
        end
    end

这对我来说有点草率。有更好的方法吗?

最佳答案

使用delete_if

array.delete_if do |v|
    if v.should_be_deleted?
        true
    else
        v.update
        false
    end
end

关于ruby - 在 Ruby 中迭代时删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2933366/

相关文章:

r - 将多个现有 xts 对象转换为多个 data.frames

php - 循环遍历数组 php 中的每第三个值

ruby-on-rails - HTTParty 在查询字符串中向 % 添加 25

ruby-on-rails - Thinking Sphinx - 与 bool 字段的嵌套关联

ruby - 哈希数组并向其添加值

ruby - 将记录的 created_by 字段检索到 Rails3 中传递的月份和年份?

ruby-on-rails - 给定字符集时,Rails 无法解析 Accept header

node.js - http.get请求循环关闭问题(Node)

c++ - 在循环c++中重用线程

c++ - 如何迭代 C++ 字符串 vector ?