Ruby Method of the Day - String.rstrip

Posted by Kelly McCauley on Sep 25, 2007

Signature

string.rstrip   #=> new_string

String.rstrip is the counter whitespace removal method to String.lstrip. string.rstrip returns a new string with trailing whitespace removed.

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"foo bar  \r\n\t".rstrip    #=> "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 obove paragraph with
# trailing whitespace removed and the string '[eol]'
# appended to the end of the line.
text.each_line{|l| puts l.rstrip << '[eol]'}

Documentation Reference

www.ruby-doc.org : String.rstrip