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

梦想与她 提交于 2019-12-28 16:44:13

问题


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?


回答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.




回答2:


var = gets.chomp 

This puts it all on one line for you.




回答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"



回答4:


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.



来源:https://stackoverflow.com/questions/6432524/why-does-rubys-gets-includes-the-closing-newline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!