steenslag
steenslag

Reputation: 80065

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

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?

Upvotes: 20

Views: 8011

Answers (5)

Tom
Tom

Reputation: 432

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

Upvotes: 0

Ben Garvey
Ben Garvey

Reputation: 73

var = gets.chomp 

This puts it all on one line for you.

Upvotes: 4

Michael Kohl
Michael Kohl

Reputation: 66837

If you look at the documentation of IO#gets, you'll notice that the method takes an optional parameter sep which defaults to $/ (the input record separator). You can decide to split input on other things than newlines, e.g. paragraphs ("a zero-length separator reads the input a paragraph at a time (two successive newlines in the input separate paragraphs)"):

>> gets('')
dsfasdf
fasfds


dsafadsf    #=> "dsfasdf\nfasfds\n\n"

Upvotes: 2

J-_-L
J-_-L

Reputation: 9177

Like puts (which sounds similar), it is designed to work with lines, using the \n character.

gets takes an optional argument that is used for "splitting" the input (or "just reading till it arrives). It defaults to the special global variable $/, which contains a \n by default.

gets is a pretty generic method for readings streams and includes this separator. If it would not do it, parts of the stream content would be lost.

Upvotes: 7

Coderer
Coderer

Reputation: 27254

From a performance perspective, the better question would be "why should I get rid of it?". It's not a big cost, but under the hood you have to pay to chomp the string being returned. While you may never have had a case where you need it, you've surely had plenty of cases where you don't care -- gets s; puts stuff() if s =~ /y/i, etc. In those cases, you'll see a (tiny, tiny) performance improvement by not chomping.

Upvotes: 0

Related Questions