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

后端 未结 4 792
醉话见心
醉话见心 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: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.

提交回复
热议问题