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

后端 未结 4 776
醉话见心
醉话见心 2020-11-30 12:16

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?

相关标签:
4条回答
  • 2020-11-30 12:49

    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.

    0 讨论(0)
  • 2020-11-30 12:54

    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"
    
    0 讨论(0)
  • 2020-11-30 12:55

    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.

    0 讨论(0)
  • 2020-11-30 12:56
    var = gets.chomp 
    

    This puts it all on one line for you.

    0 讨论(0)
提交回复
热议问题