rubyguides

String#strip

str.strip -> string

strip removes both leading (left) and trailing (right) whitespace from a string. It is among the most frequently used string methods in Ruby, especially when processing user input, parsing CSV data, or cleaning up text from external sources.

Syntax

str.strip    # remove both leading and trailing whitespace

Parameters

None. This method accepts no parameters.

With no arguments to configure, strip is simple to remember and hard to misuse. The method always removes both leading and trailing whitespace in a single call, so there is no need to chain lstrip and rstrip when both ends need cleaning.

Examples

Basic usage

text = "   hello world   "

text.strip     # => "hello world"

The spaces at both ends are gone but the space between hello and world stays put because strip only touches the outermost whitespace. That is the key distinction: interior spacing is never affected, only the leading and trailing padding.

Preserving the original

dirty = "  hello  "
clean = dirty.strip

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

Because strip returns a new string, the original value remains untouched. That immutability is useful when you need both the raw and cleaned versions of the same input, for example when logging the original while processing the trimmed copy.

In-place modification

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

The strip! variant mutates the receiver directly, which avoids creating a new string object. When you are processing many short values in a loop, using the bang method can reduce allocations and keep the code intent clear—the variable itself gets cleaned, not a copy.

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

Trimming a username before checking its length is a small step that prevents a common class of validation bugs. A user might type extra spaces without realising it, and normalizing early keeps the validation rules simple and the error messages accurate.

Parsing CSV data

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

Using map(&:strip) on each field is a concise pattern that works well when every column in a row might carry extra whitespace. For CSV data from spreadsheets or exported reports, this one-liner catches the common case of cells padded with spaces.

Cleaning log lines

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

After stripping, the log line is clean enough to split reliably on whitespace. Without the trim, the leading spaces would create an empty first element in the split result, which is easy to miss in testing but breaks downstream code that assumes a two-element array.

Choosing strip for cleanup

strip is the broadest of the whitespace helpers because it trims both sides at once. That is convenient when you are normalizing user input, cleaning CSV fields, or preparing text before a comparison. If only one edge is noisy, lstrip or rstrip can be a better fit because they leave the other side untouched. When you need to mutate the original string, strip! makes the change explicit. In parsing code, that distinction often keeps the steps easy to follow and makes the intent clearer to the next reader.

It is also a good habit to decide whether whitespace is part of the data or just noise from the source. If the value came from a form, a file line, or a config entry, trimming it before validation can prevent a lot of small bugs. If the spacing matters for display or alignment, though, a more targeted helper is a better choice. strip gives you a clean middle ground when both edges should go away.

Because it changes only the ends, strip is a strong default before splitting or comparing values that came from outside the program. That keeps the core content intact and removes the accidental padding that often sneaks in from files or pasted text. If you need to keep one edge intact for formatting, the narrower helpers remain the better choice.

That pattern is useful in validation code too, because you can normalize once and then make the later checks against a cleaner string. The result is less noise in the conditionals and fewer surprises caused by an extra space at the start or end of a value.

See Also