Section 2.19. Trimming Whitespace from a String

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 string" (no newline) s3 = s2.chop!           # s2 is now "Some string" also s4 = "Other string\r\n" s4.chop!                # "Other string" (again no newline)

Note that the "in-place" version of the method (chop!) will modify its receiver.

It is also important to note that in the absence of a trailing newline, the last character will be removed anyway:

str = "abcxyz" s1 = str.chop           # "abcxy"

Because a newline may not always be present, the chomp method may be a better alternative:

str = "abcxyz" str2 = "123\n" str3 = "123\r" str4 = "123\r\n" s1 = str.chomp          # "abcxyz" s2 = str2.chomp         # "123" # With the default record separator, \r and \r\n are removed # as well as \n s3 = str3.chomp         # "123" s4 = str4.chomp         # "123"

There is also a chomp! method as we would expect.

If a parameter is specified for chomp, it will remove the set of characters specified from the end of the string rather than the default record separator. Note that if the record separator appears in the middle of the string, it is ignored:

str1 = "abcxyz" str2 = "abcxyz" s1 = str1.chomp("yz")   # "abcx" s2 = str2.chomp("x")    # "abcxyz"

The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: