简体   繁体   中英

Is there a time when 'gets' would be used without 'chomp'?

When collecting user input in Ruby, is there ever a time where using chomp on that input would not be the desired behavior? That is, when would simply using gets and not gets.chomp be appropriate.

Yes, if you specify the maximum length for input, having a "\\n" included in the gets return value allows you to tell if Ruby gave you x characters because it encountered the "\\n", or because x was the maximum input size:

> gets 5
abcdefghij
=> 'abcde'

vs:

> gets 5
abc\n
=> 'abc\n'

If the returned string contains no trailing newline, it means there are still characters in the buffer.

Without the limit on the input, the trailing newline, or any other delimiter, probably doesn't have much use, but it's kept for consistency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM