From: Xavier Noria Date: 2007-11-20T17:53:22+09:00 Subject: Re: Why does IO.readlines() keep newlines? On Nov 20, 2007, at 12:43 AM, Daniel Brumbaugh Keeney wrote: > I'm going to speculate that readlines does this because of operating > system differences in line endings. > For compatibility between most systems, it would have to remove line > feeds (\x0A) or line-feed/carriage return combinations (\x0D\x0A). Indeed that's not the case. In CRLF platforms the I/O layer handles newlines in text mode so that the programmer *always* works with "\n", no CRLF ever goes up on Windows. Nor you need to print CRLFs by hand at the Ruby level. At the Ruby level a newline is always == "\n" and has always length 1. The string "\n" is the logical newline in Ruby meaning it is portable and the I/O layer takes care of its actual representation on disk according to the runtime platform. In Java for example this works in a different way, "\n" is not portable, to write a portable newline in Java you invoke some println(). This article explains how newlines work in C-based languages. It is Perl-based but in general it applies to Ruby except that in Ruby there's no platform where "\n" == "\015". In Ruby "\n" == "\012" everywhere and that simplifies things a bit. The I/O layer in MRI is C's stdio instead of PerlIO, but the explained newline mangling in and out is analogous: http://www.onlamp.com/pub/a/onlamp/2006/08/17/understanding-newlines.html I am the author but that doesn't matter. -- fxn