I can’t get newline conversions to work while reading:
File.write('foo.txt', "foo\r\nbar\r\n")
If you are on a Window operating system, ruby will convert any “\n” in
your output to “\r\n” before actually writing to the file.
So lets look through your output and convert any
“\n” characters to “\r\n” to see what is actually written to the file.
This line:
foo\r…\n…bar…\r…\n
gets written as:
foo\r…\r\n…bar…\r…\r\n
…because there are two “\n” characters that ruby converts to “\r\n”.
It does not matter whether the “\n” is adjacent to a “\r” or not.
File.open('foo.txt', 'r', universal_newline: true) {|fh| fh.read}
# => "foo\r\nbar\r\n", no normalization performed
Are they only supposed to work for writing? If yes, why the asymmetry?
On Windows, the conversion that ruby performs when you read from a file
is to convert any “\r\n” it sees to “\n”, so this line in the file:
foo\r…\r\n…bar…\r…\r\n
gets handed to your ruby program as:
foo\r…\n…bar…\r…\n
Inside your ruby program, “\n” stands for whatever newline your system
uses. You should not attempt to use the actual newline for your
system in your output.