2.19. Trimming Whitespace from a String

The strip method removes whitespace from the beginning and end of a string. Its counterpart strip! modifies the receiver in place.

str1 = "\t  \nabc  \t\n"
str2 = str1.strip         # "abc"
str3 = str1.strip!        # "abc"
# str1 is now "abc" also

Whitespace, of course, consists mostly of blanks, tabs, and end-of-line characters.

If we want to remove whitespace only from the beginning or end of a string, we can use the lstrip and rstrip methods:

str = "  abc  "
s2 = str.lstrip       # "abc  "
s3 = str.rstrip       # "  abc"

There are in-place variants rstrip! and lstrip! also.

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.