Stefano Crocco
3/25/2008 4:56:00 PM
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