Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

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 systems such as UNIX, the newline character is represented internally as a linefeed (\n). On others, such as 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, as shown here:

str1 = "abcxyz"
str2 = "abcxyz"
s1 = str1.chomp("yz")   # "abcx"
s2 = str2.chomp("x")    # "abcxyz"
  • + Share This
  • 🔖 Save To Your Account