Removing during iteration in Ruby?

I iterate over a very large set of rows, which iterates over a smaller set of rows. Due to its size, this method takes some time, so to speed it up, I am trying to remove rows from a smaller set that no longer need to be used as we move. 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 

The problem I am facing is that the simple way array.delete(string) effectively adds a break statement to the inner loop, which will ruin 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 

It seems to me careless. Is there a better way to do this?

+12
ruby loops
May 29 '10 at 1:11
source share
2 answers

use delete_if

 array.delete_if do |v| if v.should_be_deleted? true else v.update false end end 
+36
May 29 '10 at 7:27
source share

use 'arr.shift'

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

Output:

[1, 2, 3, 4]
[2, 3, 4]
[3, 4]
[four]

-one
Mar 14 '13 at 13:33
source share



All Articles