Ruby Method of the Day - String.strip

Posted by Kelly McCauley on Sep 27, 2007

Signature

string.strip    #=> new_string

The String.strip method is in the same family of methods as String.lstrip and String.rstrip.

string.strip returns a new string with the leading and trailing whitespace removed.

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
"foo bar  \r\n\t".strip           #=> "foo bar"
"\r\n\t  foo bar".strip           #=> "foo bar"
"\r\n\t  foo bar  \r\n\t".strip   #=> "foo bar"

text = <<-"END"
      Lorem ipsum dolor sit amet, consectetuer      \t
      adipiscing elit. Ut ac nulla.  Duis sed est.  \t
      Praesent at dui et velit tempor cursus.       \t
      Morbi purus tortor, tempus tincidunt,         \t
      placerat sit amet, dignissim quis, nulla.     \t
      Duis ipsum. Proin fringilla.
END

# Prints out each line of the above paragraph with
# both leading and trailing whitespace removed and
# the string '[eol]' appended to the end of the
# line.
text.each_line{|l| puts l.strip << '[eol]'}

Documentation Reference

www.ruby-doc.org : String.strip