From: "Jesús Gabriel y Galán" Date: 2010-03-26T01:34:16+09:00 Subject: Re: index of string from beginning of line vs beginning of file On Thu, Mar 25, 2010 at 5:19 PM, Jesse B. wrote: > I am trying to write a basic script to implement "silent comments" > In the example anything from "input.txt" that is enclosed between "--/" > and "/--" will not be output to "output.text" It appears that the > problem I am having is that the opening string is indexed from beginning > of file, whereas the closing string is indexed from beginning of line. > So I would like to figure out why. > Also when using Ruby1.9 there is an error message about using "each" > with a string that I need to find a workaround to. > any help is greatly appreciated. thanks in advance. > here is the code: > > infile = IO.readlines('input.txt','').to_s > outfile = File.new("output.txt", "w") > begins = "--/" > ends = "/--" > start_ss = infile.index(begins) > end_ss = infile.index(ends) > infile[start_ss, end_ss] = "" Check: http://ruby-doc.org/core/classes/String.html#M000771 It says: If passed two Fixnum objects, returns a substring starting at the offset given by the first, and a length given by the second. So the second parameter should be the length of the text, not the index of the token. Try this: infile[start_ss, (end_ss - start_ss)] #untested > infile.each { >  |i| >  outfile.write i >  } >  puts start_ss >  puts end_ss > outfile.close() It's also better to use the block form of File.open to ensure proper closing, even after an exception. You could also try something like this: infile = File.read("input.txt") File.open("output.txt", "w") do |outfile| outfile.puts infile.split(%r{--/.*?/--}m) end Take into account that neither this nor the above solution with indexes supports nested comments. Jesus.