From: Daniel Brumbaugh Keeney Date: 2007-11-20T08:43:11+09:00 Subject: Re: Why does IO.readlines() keep newlines? On Nov 19, 2007 1:15 PM, Just Another Victim of the Ambient Morality wrote: > At the very least, the win32 implementation of Ruby's IO.readlines() > method keeps the newline character on each string in the array. Considering > that it is the newline that defines a "line," it would not be wholly > unreasonable to omit it from the array, returned. I would have imagined > that it was implemented using String.split(), which omits the splitting > character. On a simply practical note, I'm sure the former is more popular > than the latter in the following: > > > out = File.open('file.txt', 'r'){|file| file.readlines.collect{|line| > line.chomp}} > out = File.open('file.txt', 'r'){|file| > } > > > ...in that rarely do people actually want newlines in their strings. > Interestingly enough, I discovered this behaviour from a bug in a > program which was hidden by another peculiar function, puts(). Can you > imagine my surprise that puts() not only appends a newline to a string > printed to stdout but, if a newline already exists, it doesn't bother > appending one! So, printing strings with puts() can hide whether strings > have a newline or not. Weird... > So, who thinks my suggested change is a good idea? How do I go about > popularizing my opinion? > Thank you... > 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). I personally rather prefer the current behavior of readline. I don't think puts matters, and is certainly not worth changing. I'm aware of their behavior and if it matters, I code accordingly. humbly, Daniel Brumbaugh Keeney