How to keep line endings in Ruby on Windows?
I am running Ruby 1.9.3 on Windows. When I run the following piece of code
text = File.read(path) File.write(path, text)
I am getting the same file when the file has CR + LF line endings. When I run this on a file with LF line ending, it jumps to CR + LF line ending.
How can I read and write to a file using Ruby on Windows so that line endings are preserved, whether CR + LF or LF?
Ruby, along with Perl and probably Python, know about the OS the code is running on and will automatically set what lines should be.
If you read and then write a text file, these settings will be entered and you will see that the file has changed, as you did.
If you need the file not to change, add a flag b
to open
, for example:
File.open('path', 'wb') do |fo|
fo.write(text)
end
See " IO Open Mode" for more information .