On Thu, Mar 25, 2010 at 5:19 PM, Jesse B. <jessebos / aol.com> 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 =3D IO.readlines('input.txt','').to_s
> outfile =3D File.new("output.txt", "w")
> begins =3D "--/"
> ends =3D "/--"
> start_ss =3D infile.index(begins)
> end_ss =3D infile.index(ends)
> infile[start_ss, end_ss] =3D ""

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 {
> =A0|i|
> =A0outfile.write i
> =A0}
> =A0puts start_ss
> =A0puts 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 =3D 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.