On Wednesday 16 May 2001 07:55, Angus McIntyre wrote:
> I'm playing around with Ruby, and I've come across something I can't
> quite figure out, to do with 'gsub'.
>
> My test script reads strings from a file and subsequently prints them
> out. The read strings contain "\n" sequences which, in my naive way,
> I had hoped Ruby would turn into newlines when printed out. It seems
> that although Perl might do this, Ruby doesn't. To Ruby, these look
> like '\' + 'n', not '\n'.
>
> Which is fair enough. So I try to do a 'gsub' on the string to
> replace them. And this is where the weirdness starts.
>
> I've written:
>
> 	string = string.gsub(/\\n/,"\n")
>
> (not knowing quite how destructive operations are handled in Ruby, I
> don't know if 'string.gsub!' would be safe to use in place of 'string
> = ...').
>
> The regular expression picks up the embedded '\' + 'n' and replaces
> it ... but I'm not sure with what. If I use almost anything except
> "\n", I get what I expect in the output. If I use "\n", not only do I
> not seem to get the newline I'm expecting, but it seems to munch the
> preceding character. I've piped the output through 'od -c', and it
> really seems that my newlines aren't there.
>
> This is with Ruby 1.4.2 running on LinuxPPC (I'm still trying to build
> 1.6.3).
>
> Is this a bug in that version of Ruby, something weird about Ruby in
> general, or is it a case of
> 'problem-exists-between-chair-and-keyboard'?
>
> Thanks in advance
>
> 	Angus

What platform? What version of Ruby?

FWIW Ruby 1.62 in both Linux and Win98, the following

ruby -e 'print File.open("test.txt").readlines.to_s'

yields

Mow is the time
for all great men
to come to the aid
of their country!

while

ruby -e 'print File.open("test.txt").readlines.to_s.gsub!("\n","\s")'

yields

Now is the time for all great men to come to the aid of their country

(the above ^ as one line; it may be split in email)


and ruby -e 'print File.open("test.txt").readlines.to_s.gsub!("\n","\n")'

yields the same as the first example.

test.txt was created on Linux witn cat. Same file was used in test on Linux 
and Win98.

Hope this helps :-)

regards,

Kent Starr
elderburn / mindspring.com