String#rstrip
str.rstrip -> new_string The rstrip method removes trailing whitespace (spaces, tabs, newlines) from the right end of a string, returning a new string. The original string remains unchanged.
Basic usage
# Remove trailing spaces
"hello ".rstrip # => "hello"
"hello\t".rstrip # => "hello"
"hello\n".rstrip # => "hello"
# Multiple whitespace
"hello \t\n".rstrip # => "hello"
After removing trailing characters, the resulting string is often shorter than the original. This matters when you need exact character counts later, or when comparing strings that originated from different sources. The cleaned version is a new string object, so the original text is still available if you need it. Use this technique whenever input arrives with unpredictable trailing whitespace.
Practical examples
Input cleaning
# Clean user input
username = gets.rstrip # Removes newline automatically in some cases
# Clean file content
lines = File.readlines("data.txt")
clean_lines = lines.map(&:rstrip)
When reading from files or user input, trailing newlines and spaces are common artifacts that get in the way of comparison logic. Stripping them from the right side normalizes the content without touching leading whitespace, which might be significant for indentation-sensitive processing. The rstrip call is especially useful in test assertions where the expected value comes from a clean string literal.
String comparison
# Without rstrip, these differ
"hello " == "hello" # => false
"hello ".rstrip == "hello" # => true
Comparing strings byte-for-byte is the simplest correctness check, and removing trailing noise before the comparison prevents false negatives. This is particularly useful when data comes from external sources where line endings or trailing spaces are inconsistent. The comparison itself becomes deterministic rather than sensitive to minor formatting differences.
CSV processing
# CSV lines often have trailing whitespace
csv_data = "name,email,value\n"
csv_data.rstrip
CSV data frequently arrives with trailing whitespace from spreadsheet exports or hand-edited files. Cleaning these lines with rstrip before splitting on commas avoids empty trailing fields and keeps the parsed columns predictable. The method works on the entire line at once, so a single call handles all trailing characters without needing to iterate over individual fields.
Path handling
# Clean trailing slashes
path = "/usr/local/bin/"
path.rstrip # => "/usr/local/bin"
File paths with trailing slashes can cause problems in join operations or when constructing relative paths. Removing the trailing separator with rstrip normalizes the path, but note that this only strips the slash character itself; it does not interpret or validate the path. For more comprehensive path handling, Ruby’s Pathname class offers richer manipulation.
Text processing
text = <<~TEXT
Line one
Line two
Line three
TEXT
text.rstrip # Removes trailing blank lines
Heredoc text blocks often include trailing spaces and blank lines that were part of the original indentation. Calling rstrip on the entire text removes those trailing artifacts in one pass. The result is a clean string with only the meaningful content, ready for further processing or display.
In-place version
# rstrip returns new string
str = "hello "
result = str.rstrip
puts str # => "hello " (unchanged)
puts result # => "hello"
# rstrip! modifies in place
str = "hello "
str.rstrip!
puts str # => "hello"
The bang variant is the right choice when you want to update the original object and are certain the side effect will not confuse other code that holds a reference to the same string. The non-bang form is safer in shared contexts, since it returns a fresh string and leaves the original untouched. Choose based on ownership: if this code owns the string, mutating it is fine; if the string was passed in from a caller, returning a copy is more predictable.
Other strip methods
# lstrip - remove leading whitespace
" hello".lstrip # => "hello"
# strip - remove both ends
" hello ".strip # => "hello"
Each strip variant targets a specific side of the string, which means you can clean only the edge that actually matters. When you are certain the noise is only on the right, rstrip avoids disturbing leading whitespace that might carry meaning. The lstrip and strip alternatives cover the other cases, so the full family gives you precise control over which side gets cleaned without touching content you want to preserve.
Character types removed
# Spaces
"hello ".rstrip # => "hello"
# Tabs
"hello\t".rstrip # => "hello"
# Newlines
"hello\n".rstrip # => "hello"
"hello\r\n".rstrip # => "hello" (Windows)
# Vertical tabs, form feeds
"hello\v".rstrip # => "hello"
The characters that rstrip removes include spaces, tabs, newlines, carriage returns, vertical tabs, and form feeds. This covers the whitespace characters defined by the POSIX [:space:] class and the ASCII whitespace range. Knowing the exact set of characters affected helps you predict the method’s behavior when processing text from different operating systems or encoding sources.
Use cases
- Cleaning user input
- File line processing
- String normalization
- Path manipulation
- Text formatting
When trailing space matters
rstrip is the right tool when the useful text is already at the left edge and the noise is only at the end. It is common after reading lines from files, processing form input, or preparing values for comparison. Because it leaves leading whitespace intact, it is safer than strip when indentation or alignment still matters. If you want to change the string in place, use rstrip!; otherwise, keep the original value and work with the returned copy. That choice is often clearer in parsing code.
That choice matters in parsing code because it makes the next step easier to trust. If the string still needs leading spaces for display or for a later split, keeping them intact avoids extra cleanup. If the trailing whitespace is just a line ending from file input, rstrip gives you a clean value without changing the meaning at the start of the line.
rstrip is also handy when comparing file-derived text that should be equal even if the source added a trailing gap or newline. It lets the code focus on the content itself instead of a formatting artifact at the end of the line. That keeps comparisons, logging, and line-oriented parsing a little easier to reason about.
The method also fits nicely in read pipelines where the trailing space is expected noise. It lets the parser clean up the end of a line without changing the left edge, which can matter if the start of the string still carries meaning. In those cases the code stays specific instead of making every line look the same before it is actually needed.