Ruby example

How to trim whitespace from a string in Ruby

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Use strip: " hello \n".strip returns "hello". lstrip trims only the start and rstrip only the end. To remove every whitespace character, inner ones too, use text.gsub(/\s+/, ""); to collapse runs of whitespace into single spaces, use text.split.join(" ").

Ruby calls trimming strip, where JavaScript says trim(). It returns a new string and leaves the original alone; strip! changes the string in place. The sections below cover trimming the ends, removing or collapsing whitespace inside the string, the non-breaking spaces that strip does not see, the nil that strip! returns, cutting the first or last characters, and removing a substring with sub, gsub, slice! or tr, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1Trim both ends: strip, lstrip and rstripRecommended

strip removes leading and trailing whitespace: spaces, tabs, newlines, carriage returns, vertical tabs, form feeds and null bytes ("\0"). Whitespace between words stays. lstrip trims only the left (start) and rstrip only the right (end). All three return a new string, so assign or use the result. Calling strip on nil raises NoMethodError; use &. or to_s when a value may be missing. On this page (Ruby 4.0.7) the three methods also take the characters to remove, written like tr's character sets; Ruby 3.4 and earlier accept no argument.

strip.rb
raw = "  \t Hello, world! \n"

p raw.strip
p raw.lstrip
p raw.rstrip

# Typical use: clean up a line of input
name = "   Ada Lovelace  \n"
puts "Hello, #{name.strip}!"

# Whitespace between words stays
p "  two  words  ".strip

# Tabs, newlines, \v, \f, \r and null bytes go too
p " \v\f\r\0 data \0\n".strip

# nil has no strip: use &. or to_s
line = nil
p line&.strip
p line.to_s.strip

# Ruby 4.0: name the characters to strip
p "--title--".strip("-")
p "xyhiyx".strip("xy")

Output

strip prints "Hello, world!", lstrip keeps the trailing " \n" and rstrip keeps the leading " \t ". The double space in "two words" survives because only the ends are trimmed. line&.strip gives nil and line.to_s.strip gives "". The last two lines print "title" and "hi": each character in the argument is stripped, in any order, not the argument as a whole word. For code that must run on older Rubies, use a regex such as s.gsub(/\A-+|-+\z/, "").

2Remove or collapse whitespace inside the string

strip never touches the middle of a string. To remove every whitespace character, use gsub(/\s+/, "") (\s matches space, tab, newline, carriage return, vertical tab and form feed) or list the characters for delete. delete(" ") removes plain spaces only. To normalize text instead, collapse each run of whitespace into one space: split with no argument splits on any whitespace and drops the empty pieces, so split.join(" ") trims and collapses in one go (Rails calls this squish, an ActiveSupport method). squeeze collapses runs of a repeated character and is the right tool when only spaces repeat.

inner_whitespace.rb
text = "  Ruby   is \t fun \n"

# Remove every whitespace character
p text.gsub(/\s+/, "")
p text.delete(" \t\r\n")

# delete(" ") removes spaces only: the tab and newline stay
p text.delete(" ")

# Collapse runs of whitespace into one space, trim the ends
p text.split.join(" ")
p text.gsub(/\s+/, " ").strip

# squeeze(" ") collapses runs of spaces only, ends included
p text.squeeze(" ")

# squeeze with no argument collapses any repeated character
p "aaabbbccc".squeeze
p "mississippi".squeeze("sp")

Output

Both removal lines print "Rubyisfun", while delete(" ") leaves "Rubyis\tfun\n". Both collapse lines print "Ruby is fun". squeeze(" ") turns each run of spaces into one but keeps the space at each end and the tab, giving " Ruby is \t fun \n". With no argument, squeeze collapses every repeated character ("abc"); with "sp" it collapses only those, so mississippi becomes "misisipi".

3Non-breaking and other Unicode spaces

Text pasted from web pages, Word or spreadsheets often carries a non-breaking space (U+00A0) where you expect a plain one. strip, split and the regex \s only know ASCII whitespace, so they leave it in place. Python's strip() and JavaScript's trim() do remove it, so this catches people moving to Ruby. The POSIX class [[:space:]] (or \p{Space}) matches Unicode spaces too, so trim with gsub(/\A[[:space:]]+|[[:space:]]+\z/, ""). The example prints with dump, because p shows a non-breaking space as a plain-looking space.

unicode_spaces.rb
# "\u00A0" is a non-breaking space, common in pasted text
s = "\u00A0 Price: 42\u00A0"

# strip only knows ASCII whitespace, so the NBSPs stay
puts s.strip.dump

# [[:space:]] matches Unicode spaces too
puts s.gsub(/\A[[:space:]]+|[[:space:]]+\z/, "").dump

# \s is ASCII-only in Ruby, so it misses them as well
p "\u00A0".match?(/\s/)
p "\u00A0".match?(/[[:space:]]/)

# Inner whitespace: split leaves NBSP and em space alone
words = "one\u00A0two\u2003three"
p words.split.size
p words.split(/[[:space:]]+/)
p words.gsub(/[[:space:]]+/, " ")

# Zero-width space and BOM are not whitespace at all
z = "\uFEFFtitle\u200B"
p z.gsub(/\A[[:space:]]+|[[:space:]]+\z/, "").length
p z.delete("\uFEFF\u200B")

Output

After strip the string still reads "\u00A0 Price: 42\u00A0": the leading non-breaking space shields the plain space behind it. The [[:space:]] version prints "Price: 42". /\s/ does not match U+00A0 (false) while [[:space:]] does (true), and split sees a single word where there are three. A zero-width space (U+200B) and a byte order mark (U+FEFF) are not whitespace to any of these, so the regex leaves all 7 characters; remove them by name with delete.

4Trim in place: strip! and its nil return

strip! (and lstrip!, rstrip!, squeeze!, delete_prefix! and the rest) changes the string itself instead of building a new one, so every variable that refers to that string sees the change. The catch: a bang method returns nil when it had nothing to change, so s.strip!.upcase works on padded input and crashes on clean input. Call it on its own line, or chain the non-bang form. A frozen string cannot be changed at all; that includes every literal in a file that starts with the # frozen_string_literal: true comment.

strip_in_place.rb
name = "  Ada  "
same = name
name.strip!
p name
p same

# strip! returns nil when there was nothing to remove
p "  messy ".strip!
p "clean".strip!

# So a chained bang method fails on clean input
input = "already clean"
begin
  input.strip!.upcase
rescue NoMethodError => e
  puts "NoMethodError: #{e.message}"
end

# Chain the non-bang form instead
p input.strip.upcase

# Frozen strings can't be changed in place
frozen = "  fixed  ".freeze
begin
  frozen.strip!
rescue FrozenError => e
  puts "FrozenError: #{e.message}"
end

copy = frozen.dup
copy.strip!
p copy

Output

same prints "Ada" too, because both names point at one string that strip! changed. " messy ".strip! returns "messy", but "clean".strip! returns nil, and calling upcase on that gives undefined method 'upcase' for nil. The frozen string raises can't modify frozen String: " fixed "; dup makes an unfrozen copy you can trim. In everyday code, s = s.strip is just as clear and the cost of the new string rarely matters.

5Remove the first or last characters

A negative index counts from the end, and a range with no end runs to the last character, so s[1..] drops the first character and s[0...-n] drops the last n (three dots exclude the end of the range). When you know the text to remove, delete_prefix and delete_suffix say so and do nothing when it is not there. chomp with no argument removes one trailing line ending, which is what you want for lines you read; chop removes the last character whatever it is.

first_last.rb
s = "report.csv"

# Drop the first character
p s[1..]
p s.delete_prefix("r")

# Drop the last n characters
n = 4
p s[0...-n]
p s[...-n]

# Drop a known start or end, only if it is there
p s.delete_suffix(".csv")
p s.delete_suffix(".txt")
p s.chomp(".csv")
p s.delete_prefix("report")

# chop removes the last character, chomp a line ending
p s.chop
p "line\r\n".chop
p "line\n".chomp
p "line".chomp

# Short strings
p "ab"[0...-5]
p "a"[1..]
p ""[1..]

Output

s[1..] and delete_prefix("r") both give "eport.csv"; both slices of the last four give "report". delete_suffix(".txt") returns the string unchanged because it does not end that way. chop treats "\r\n" as one character, so "line\r\n".chop is "line", and chomp leaves a string without a line ending alone, which makes it safe to call on every line. The last three lines are the edge cases: slicing off more than the string holds gives "", and so does "a"[1..], but ""[1..] is nil because index 1 is past the end of an empty string.

6Remove a substring: sub, gsub, slice! and tr

To remove text from the middle, replace it with an empty string: sub replaces the first match and gsub every match, and both accept a string or a regex. slice! removes the text in place and returns the part it took out. Two methods look similar and behave differently: delete and tr work on sets of single characters, not on substrings. tr("lo", "01") turns every l into 0 and every o into 1, while gsub("lo", "01") replaces only the two-letter sequence lo. Use tr for character-for-character swaps and gsub for words and patterns.

remove_substring.rb
text = "Hello, world, and goodbye world"

# sub removes the first match, gsub every match
p text.sub(" world", "")
p text.gsub(" world", "")
p text.gsub(/,? world/, "")

# slice! removes in place and returns what it removed
msg = "Error: disk full"
removed = msg.slice!("Error: ")
p removed
p msg

# delete takes a set of characters, not a substring
p "hello world".delete("world")
p "hello world".gsub("world", "")

# tr maps characters one to one; gsub replaces text
p "hello world".tr("lo", "01")
p "hello world".gsub("lo", "01")
p "2026-12-02".tr("-", "/")
p "snake_case_name".tr("_", " ")

Output

sub leaves the second world in place, gsub removes both, and the regex also takes the comma in front of the first one, printing "Hello, and goodbye". slice! returns "Error: " and leaves msg as "disk full"; when the text is not found it returns nil and changes nothing. delete("world") prints "he " because it deletes every w, o, r, l and d, which is rarely what you meant. The tr line prints "he001 w1r0d" where gsub prints "hel01 world".

7Which should you use?

MethodRemovesReturnsBest for
s.stripASCII whitespace at both endsNew stringTrimming input: most cases
s.lstrip / s.rstripWhitespace at one endNew stringKeeping indentation or a trailing newline
s.strip!Same as stripThe string, or nil if unchangedIn place, on its own line; never chained
s.gsub(/\s+/, "")All ASCII whitespaceNew stringRemoving every space, tab and newline
s.split.join(" ")Extra whitespaceNew stringTrimming and collapsing inner runs
s.squeeze(" ")Repeated spacesNew stringCollapsing runs of one character
gsub(/\A[[:space:]]+|[[:space:]]+\z/, "")Unicode spaces at both endsNew stringPasted text with non-breaking spaces
s.delete_prefix / delete_suffixKnown text at one endNew stringFile extensions, prefixes, units
s.delete("abc")Every a, b and cNew stringCharacters, never substrings: use gsub

Frequently asked questions

What is the Ruby equivalent of trim() in JavaScript or Java?

It is strip: " hi ".strip returns "hi". lstrip and rstrip trim only the start or the end, like trimStart() and trimEnd(). One difference: JavaScript's trim() also removes the non-breaking space U+00A0 and Ruby's strip does not, so use gsub(/\A[[:space:]]+|[[:space:]]+\z/, "") for pasted text.

How do I strip specific characters, like Python's strip("x")?

On Ruby 4.0, which this page runs, pass them: "--title--".strip("-") returns "title", and lstrip and rstrip take the same argument. Ruby 3.4 and earlier accept no argument, so use a regex there: s.gsub(/\A-+|-+\z/, ""). To remove one known prefix or suffix once, delete_prefix and delete_suffix work on every Ruby since 2.5.

Does strip remove newlines?

Yes. strip removes \n, \r\n, tabs and the other ASCII whitespace from both ends. If you only want to drop the line ending from a line you read, chomp is more precise: it removes one trailing \n, \r\n or \r and keeps any spaces.

How do I trim every string in an array or hash?

Map over it: [" a ", "b "].map(&:strip) returns ["a", "b"]. For the values of a hash, use transform_values(&:strip), which turns {name: " Ann ", city: "Oslo "} into {name: "Ann", city: "Oslo"}.

Why does strip! return nil?

Ruby's bang methods return nil when they made no change, so you can write if s.strip! to learn whether anything was trimmed. It means s.strip!.upcase raises NoMethodError (undefined method 'upcase' for nil) on a string that was already clean. Call strip! on its own line, or use s = s.strip.

What is the difference between tr and gsub?

tr swaps single characters by position in two character sets: "hello".tr("el", "ip") gives "hippo". gsub replaces each match of a string or regex with new text, so gsub("el", "ip") only changes the sequence el. Use tr (or delete) for character swaps and gsub for words and patterns.

Does plain Ruby have squish or blank?

No, squish, blank? and present? come from Rails (ActiveSupport). In plain Ruby, s.split.join(" ") does what squish does, and s.strip.empty? tells you whether a string is blank.

Run it yourself

Open any of these in the full Ruby editor to tweak, run and share.

Ruby playground