Normalizing line endings in Ruby
Since ruby 1.9 you can use String::encode
with universal_newline: true
to get all of your new lines into \n
while keeping your encoding unchanged:
s.encode(s.encoding, universal_newline: true)
Once in a known newline state you can freely convert back to CRLF using :crlf_newline
. eg: to convert a file of unknown (possibly mixed) ending to CRLF
(for example), read it in binary mode, then :
s.encode(s.encoding, universal_newline: true).encode(s.encoding, crlf_newline: true)
Best is just to handle the two cases that you want to change specifically and not try to get too clever:
s.gsub /\r\n?/, "\n"
I think the cleanest solution would be to use a regular expression:
s.gsub! /\r\n?/, "\n"