Why does Ruby's 'gets' includes the closing newline?

Viewed 7532

I never need the ending newline I get from gets. Half of the time I forget to chomp it and it is a pain in the....

Why is it there?

5 Answers

How I auto-detect line endings:

# file open in binary mode
line_ending = 13.chr + 10.chr
check = file.read(1000)
case check
when /\r\n/
  # already set
when /\n/
  line_ending = 10.chr
when /\r/
  line_ending = 13.chr
end
file.rewind

while !file.eof?
  line = file.gets(line_ending).chomp
  ...
end
Related