String#strip
str.strip -> string Returns:
String · Updated March 13, 2026 · String Methods strings whitespace strip
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 strings from external sources.
Syntax
str.strip # remove both leading and trailing whitespace
Parameters
None. This method accepts no parameters.
Examples
Basic usage
text = " 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"]