Preserve linefeeds?

I’m trying to determine how to ensure my linefeeds are preserved when
reading a file.

If I use File.open the file is read as a single line with no line feeds.
If I use IO.binread, it looks a bit better, but it too looks like it’s
dropping some of the line endings. The CSV file I’m trying to parse is
generated with multiple sections, each section has to be dealt with
differently, so I’m trying to break up the content wherever there is
‘\r\n\r\n’ (a windows box generates these files). However, it can’t
locate those line endings. However, if I read the file into a text
viewer, I can see the CRLF endings.

What’s the best way to handle this in Ruby?

Wayne

On Oct 31, 2011, at 8:49 AM, Wayne B. wrote:

I’m trying to determine how to ensure my linefeeds are preserved when reading a
file.

If I use File.open the file is read as a single line with no line feeds. If I
use IO.binread, it looks a bit better, but it too looks like it’s dropping some of
the line endings. The CSV file I’m trying to parse is generated with multiple
sections, each section has to be dealt with differently, so I’m trying to break up
the content wherever there is ‘\r\n\r\n’ (a windows box generates these files).
However, it can’t locate those line endings. However, if I read the file into a
text viewer, I can see the CRLF endings.

What’s the best way to handle this in Ruby?

When opening a file, use “b” modifier together with regular mode flags
(described in “ri IO”), e.g.:

File.open(“rb”) { |_io|
puts _io.readlines.inspect
}

This will show that “\r\n” are preserved on Windows with “b” modifier.

Gennady.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs