rubyguides

String#strip

strip removes whitespace from both ends of a string. Whitespace includes spaces, tabs, newlines, carriage returns, form feeds, and null bytes.

Signature

str.strip → new_string

Returns: A new string with leading and trailing whitespace removed.

Basic Usage

"  hello  ".strip
# => "hello"

"\tgoodbye\r\n".strip
# => "goodbye"

"  multiple   spaces   ".strip
# => "multiple   spaces"

What Counts as Whitespace

Ruby defines whitespace as the characters matching /\s/, which includes:

  • " " (space)
  • "\t" (tab)
  • "\n" (newline)
  • "\r" (carriage return)
  • "\f" (form feed)
  • "\v" (vertical tab)
  • "\0" (null byte)
" \t\n\r\0\f\v hello \t\n\r\0\f\v ".strip
# => "hello"

lstrip and rstrip

Remove from one end only:

# left side only
"  hello  ".lstrip
# => "hello  "

# right side only
"  hello  ".rstrip
# => "  hello"

strip! (bang variant) modifies the string in place and returns nil if no whitespace was removed:

original = "  hello  "
original.strip!
# => "hello"
original
# => "hello"

Practical Examples

Cleaning User Input

Form input often arrives with accidental whitespace:

def normalize(input)
  input.to_s.strip
end

normalize("  john.doe@example.com ")
# => "john.doe@example.com"

Parsing Line-Oriented Data

When reading lines from a file, strip removes the trailing newline and any extra padding:

File.readlines("data.csv").each do |line|
  name, value = line.strip.split(",")
  puts "#{name}: #{value}"
end

Comparing Strings Gracefully

query = "  ruby  ".strip.downcase

if query == "ruby"
  puts "Exact match"
end

In-Place Modification with strip!

The bang variant modifies the receiver:

s = "  text  "
result = s.strip!
# s is now "text"
# result is "text" (also returns the new string)

# If no whitespace, returns nil:
s2 = "text"
result2 = s2.strip!
# s2 is still "text"
# result2 is nil

Common Pitfalls

Non-Breaking Spaces

Unicode category U+00A0 (non-breaking space) is not removed by strip because it does not match /\s/:

"\u00A0hello\u00A0".strip
# => "\u00A0hello\u00A0" (unchanged)

# To remove non-breaking spaces too:
"\u00A0hello\u00A0".strip.gsub("\u00A0", "")
# => "hello"

Mixed Whitespace in the Middle

strip only removes from the ends, not the middle of the string:

"hello    world".strip
# => "hello    world" (middle spaces unchanged)

# For collapsing all whitespace:
"hello    world".split.join(" ")
# => "hello world"

See Also