在Ruby中迭代时删除? [英] Deleting While Iterating in Ruby?

查看:112
本文介绍了在Ruby中迭代时删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm iterating over a very large set of strings, which iterates over a smaller set of strings. Due to the size, this method takes a while to do, so to speed it up, I'm trying to delete the strings from the smaller set that no longer needs to be used as it goes along. Below is my current code:

    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语句,从而弄乱了结果.我知道如何解决此问题的唯一方法是执行以下操作:

The problem I face is that the easy way, array.delete(string), effectively adds a break statement to the inner loop, which messes up the results. The only way I know how to fix this is to do this:

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

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

This feels kind of sloppy to me. Is there a better way to do this?

推荐答案

使用delete_if

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

这篇关于在Ruby中迭代时删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆