From: Stefano Crocco Date: 2008-03-26T01:56:26+09:00 Subject: Re: remove regex matched line question On Tuesday 25 March 2008, Ikuta Lin wrote: > I wrote the code to query a txt file, and tried remove matched line like > as below > but it not work as well, can someone help? > ------------------------ > code: > > src = File.open("./src.txt").readlines > puts src.inspect > src.collect do |e| > if e=~/^(#)/ > src.delete(e) > end > end > puts src.inspect > ------------------------- > txt > > #/etc/passwd > #/etc/shadow > /etc/group > > ------------------------ > problem > ["#/etc/passwd \r\n", "#/etc/shadow \r\n", "/etc/group \r\n"] > ["#/etc/shadow \r\n", "/etc/group \r\n"] > ------------------ > still available? If I understand you correctly, you want to remove from the array src all the lines which start with #. In this case, you want reject: src.delete_if{|l| l.match =~/^#/} It's usually unwise to remove (and maybe also to add) items to an array while iterating on it using each or similar methods. I hope this helps Stefano