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.