String#lstrip

str.strip -> string
Returns: String · Updated March 13, 2026 · String Methods
strings whitespace strip

These three methods remove whitespace from strings: lstrip removes leading (left) whitespace, rstrip removes trailing (right) whitespace, and strip removes both. They are among the most frequently used string methods in Ruby, especially when processing user input, parsing CSV data, or cleaning up strings from external sources. All three methods return a new string by default, leaving the original unchanged. The in-place variants lstrip!, rstrip!, and strip! modify the string directly.

Syntax

str.lstrip   # remove leading whitespace only
str.rstrip   # remove trailing whitespace only
str.strip    # remove both leading and trailing whitespace

Parameters

None. These methods accept no parameters.

Examples

Basic usage

text = "   hello world   "

text.lstrip    # => "hello world   "
text.rstrip    # => "   hello world"
text.strip     # => "hello world"

Preserving the original

dirty = "  hello  "
clean = dirty.strip

dirty  # => "  hello  " (unchanged)
clean  # => "hello"

In-place modification

name = "  John Doe  "
name.strip!   # modifies name directly
name          # => "John Doe"

Common Patterns

Form validation

def validate_username(username)
  username.strip!
  username.length >= 3 && username.length <= 20
end

validate_username("  alice  ")  # => true
validate_username("ab")         # => false

Parsing CSV data

row = ["  1", "  Alice  ", "  25  "]
id, name, age = row.map(&:strip)
# => [1, "Alice", 25]

Cleaning log lines

log_line = "   [INFO] Application started   "
level, message = log_line.strip.split(/\s+/, 2)
# => ["[INFO]", "Application started"]

In-Place Variants

The bang methods modify the string directly:

text = "  hello  "
text.strip!   # returns "hello" if whitespace was removed, nil otherwise
text           # => "hello"

Use these when you want to avoid allocating a new string object.

See Also