2.18. Removing Trailing Newlines and Other Characters

Often we want to remove extraneous characters from the end of a string. The prime example is a newline on a string read from input.

The chop method removes the last character of the string (typically a trailing newline character). If the character before the newline is a carriage return (\r), it will be removed also. The reason for this behavior is the discrepancy between different systems’ conceptions of what a newline is. On some systems such as UNIX, the newline character is represented internally as a linefeed (\n). On others such as DOS and Windows, it is stored as a carriage return followed by a linefeed (\r\n).

str = gets.chop # Read string, remove newline s2 = "Some string\n" # "Some ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.