From: Brian Candler Date: 2011-02-02T05:59:50+09:00 Subject: Re: Search String and Delete Line Containing String Bob Hatch wrote in post #978955: > I am new to Ruby and am pulling my hair out on something that I know is > simple. I am searching a large text file, line by line for text that > will reside in part of the line. If it finds part of the text, I want to > delete the line. Here is what I have that is not working. Help is > appreciated! Thanks in advance! > > # process every line in a text file > file='c:\ruby192\my_projects\IIS_Logs\ex11012607.log' > text=File.readlines(file).each do |line| > search_text = "/memberinfo/downline/tree/canvas.asp" > if(line.gsub!(search_text) == search_text) then gsub! returns the whole line after the substitution has taken place, or nil if no substitution has taken place. So you should test for nil/not nil, not compare against the substitution text. irb is the way to find this sort of thing out: $ irb --simple-prompt >> line = "foo bar baz" => "foo bar baz" >> line.gsub!("bar", "xxx") => "foo xxx baz" >> line.gsub!("zzz", "xxx") => nil Also, gsub! should take two arguments as I've shown. But rather than raise an error, the joys of ruby 1.9/1.8.7 mean that it does something unexpected when you give it one argument: >> line.gsub!("zzz") => # It returns an Enumerator object. In this case, I'd say that's pretty confusing behaviour, and very rarely useful. It's because there is a one-argument form of gsub which takes a block: >> line.gsub!("foo") { (1+2).to_s } => "3 xxx baz" And if you omit the block, it's returning an enumerator for consistency with each/map/select, which return an enumerator when invoked without a block (also not particularly useful IMO). -- Posted via http://www.ruby-forum.com/.