Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 411
steenslag Avatar asked Jun 21 '11 21:06

steenslag


People also ask

How do you stop a new line in Ruby?

You need to use "\n" not '\n' in your gsub.

How do you make a new line in Ruby?

"\n" is newline, '\n\ is literally backslash and n.

How do you leave a line in Ruby?

\r\n should probably do the trick.

What is trailing new line?

When a line break occurs at the end of a block of text, it is called a trailing newline. The newline character is important in computer programming, since it allows programmers to search for line breaks in text files.


2 Answers

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.

like image 112
J-_-L Avatar answered Oct 05 '22 13:10

J-_-L


var = gets.chomp 

This puts it all on one line for you.

like image 23
Ben Garvey Avatar answered Oct 05 '22 12:10

Ben Garvey