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?


Solution 1:

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.

Solution 2:

var = gets.chomp 

This puts it all on one line for you.

Solution 3:

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"