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

65 Views Asked by At

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.chompbe appropriate.

1

There are 1 best solutions below

0
On BEST ANSWER

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.