Home > Articles > Programming > Ruby

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

2.19 Trimming Whitespace from a String

The strip method removes whitespace from the beginning and end of a string, whereas 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.

  • + Share This
  • 🔖 Save To Your Account