rubyguides

String#lstrip

str.strip -> string

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

The syntax is straightforward because these methods are mostly about choosing which edge of the string should change. That makes them easy to place in cleanup code, especially when the input is coming from a form, a file, or another system that may have left extra spaces behind.

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"

This example shows why the three methods are grouped together: they solve the same problem from different angles. When the source text has uneven spacing, picking the narrowest method that fits keeps the intent of the code very clear.

Preserving the original

dirty = "  hello  "
clean = dirty.strip

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

Keeping the original string intact is often the safest choice when the same value might be reused in several places. Returning a cleaned copy makes the transformation obvious and avoids surprising later code that still expects the old spacing. This non-mutating behavior is the norm for most string methods in Ruby unless a bang variant is used explicitly.

In-place modification

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

The bang version is best used when you intentionally want to overwrite the original value. That can be convenient in a small script or a tight loop, but it is worth being explicit because the call changes the object in place. When you see a bang method in Ruby, the convention signals that the receiver may be modified, so using the non-bang form is a safer default unless the mutation is clearly intended.

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

Validation code often starts with trimming because extra spaces should not count toward the actual content. Combining cleanup with a length check keeps the rule compact, and it makes the expected input shape easy to understand. Moving the trim step before the validation logic also means the check itself does not need to account for stray spaces, which keeps the guard clause focused on the real constraints.

Parsing CSV data

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

Mapping across each field works well when the same cleanup step applies to every value. That keeps the parsing code compact and avoids repeating the same trimming call for each column. This pattern is also easy to extend when new columns appear, since the transformation stays the same regardless of how many fields are in the row.

Cleaning log lines

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

Log lines often need one cleanup step before they are split into parts. Trimming the line first makes the later split simpler and keeps extra spaces from turning into accidental empty fields.

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.

The return value of the bang method is worth remembering because it tells you whether anything changed. That can be useful if you want to branch on whether cleanup actually happened, especially in a routine that only wants to record or react to modified input.

Choosing the right variant

lstrip, rstrip, and strip each solve a slightly different problem, so the best choice depends on where the extra whitespace lives. When the data comes from a human typing into a form, strip is often the safest default because it cleans both ends at once. When formatting matters and only one side should change, the narrower methods are a better fit.

The bang versions can be handy in tight loops or short scripts, but they are most useful when you already know the original string should change. If you are passing strings around to other parts of the program, returning a new cleaned value is usually easier to reason about.

See Also