I thought this code would work, but the regular expression doesn’t ever match the \r\n. I have viewed the data I am reading in a hex editor and verified there really is a hex D and hex A pattern in the file.
I have also tried the regular expressions /\xD\xA/m and /\x0D\x0A/m but they also didn’t match.
This is my code right now:
lines2 = lines.gsub( /\r\n/m, '\n' ) if ( lines == lines2 ) print 'still the same\n' else print 'made the change\n' end
In addition to alternatives, it would be nice to know what I’m doing wrong (to facilitate some learning on my part). 🙂
What do you get when you do
puts lines? That will give you a clue.By default
File.openopens the file in text mode, so your\r\ncharacters will be automatically converted to\n. Maybe that’s the reasonlinesare always equal tolines2. To prevent Ruby from parsing the line ends use therbmode:C:\> copy con lala.txt a file with many lines ^Z C:\> irb irb(main):001:0> text = File.open('lala.txt').read => 'a\nfile\nwith\nmany\nlines\n' irb(main):002:0> bin = File.open('lala.txt', 'rb').read => 'a\r\nfile\r\nwith\r\nmany\r\nlines\r\n' irb(main):003:0>But from your question and code I see you simply need to open the file with the default modifier. You don’t need any conversion and may use the shorter
File.read.