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?
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.
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"
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.
var = gets.chomp
This puts it all on one line for you.