String#rstrip

str.rstrip -> new_string
Returns: String · Updated March 13, 2026 · String Methods
strings whitespace trimming cleaning

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"

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)

String Comparison

# Without rstrip, these differ
"hello " == "hello"   # => false
"hello ".rstrip == "hello"  # => true

CSV Processing

# CSV lines often have trailing whitespace
csv_data = "name,email,value\n"
csv_data.rstrip

Path Handling

# Clean trailing slashes
path = "/usr/local/bin/"
path.rstrip  # => "/usr/local/bin"

Text Processing

text = <<~TEXT
  Line one
  Line two   
  Line three
      
TEXT

text.rstrip  # Removes trailing blank lines

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"

Other Strip Methods

# lstrip - remove leading whitespace
"   hello".lstrip   # => "hello"

# strip - remove both ends
"   hello   ".strip  # => "hello"

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"

Use Cases

  • Cleaning user input
  • File line processing
  • String normalization
  • Path manipulation
  • Text formatting

See Also