代码之家  ›  专栏  ›  技术社区  ›  Jesse Jashinsky

在Ruby中迭代时删除?

  •  14
  • Jesse Jashinsky  · 技术社区  · 16 年前

    我在一个非常大的字符串集合上迭代,它在一个较小的字符串集合上迭代。由于大小的原因,这个方法需要一段时间才能完成,所以为了加快速度,我尝试从较小的集合中删除不再需要使用的字符串。以下是我目前的代码:

        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)

    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
    

    我觉得这有点马虎。有没有更好的办法?

    2 回复  |  直到 12 年前
        1
  •  38
  •   horseyguy    16 年前

    使用 delete_if

    array.delete_if do |v|
        if v.should_be_deleted?
            true
        else
            v.update
            false
        end
    end
    
        2
  •  -1
  •   Abhishek    10 年前

    使用“arr.shift”

    a=[1,2,3,4]
    while(a.length!=0)
      print a
      a.shift
      print "\n"
    end
    

    输出:


    [2, 3, 4]

    [4]

    推荐文章