Section 2.20. Repeating Strings


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.




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

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net