Question
In Ruby, what method should be used to remove whitespace from a string? I am looking for the Ruby equivalent of PHP's trim() and also want to understand how to remove whitespace from the beginning, end, or throughout a string.
text = " hello world "
What Ruby method should I use if I want behavior similar to PHP's trim()?
Short Answer
By the end of this page, you will understand how Ruby removes whitespace from strings using strip, lstrip, rstrip, and gsub. You will also learn which method matches PHP's trim(), when to remove whitespace only from the ends of a string, and when to remove all whitespace characters everywhere in the string.
Concept
Ruby has several string methods for removing whitespace, and each one solves a slightly different problem.
The most important one is strip:
" hello ".strip
# => "hello"
This is the Ruby method most similar to PHP's trim(). It removes whitespace from both the beginning and the end of a string.
Ruby also provides:
lstrip— removes whitespace from the left/start onlyrstrip— removes whitespace from the right/end onlygsub— replaces matching text, useful when you want to remove whitespace everywhere in the string
For example:
" hello world ".lstrip
# => "hello world "
" hello world ".rstrip
# => " hello world"
" hello world ".gsub(/\s+/, "")
# => "helloworld"
Why this matters:
- User input often includes accidental spaces.
- Form fields may need cleanup before validation.
- CSV, API, and file data often need normalization.
- Comparing strings without trimming can produce bugs.
A key detail: strip does not remove spaces in the middle of the string. It only removes whitespace at the edges. If you need to remove all whitespace characters, use a replacement approach such as gsub(/\s+/, "").
Mental Model
Think of a string like a piece of paper with empty margins.
stripcuts off the empty margins on both sides.lstripcuts off only the left margin.rstripcuts off only the right margin.gsub(/\s+/, "")removes every blank area, even between words.
So if your text is:
" hello world "
Then:
stripgives you the clean sentencelstripkeeps the right-side paddingrstripkeeps the left-side paddinggsubsqueezes everything together if you remove all whitespace entirely
Syntax and Examples
Core syntax
string.strip
string.lstrip
string.rstrip
string.gsub(/\s+/, "")
Example 1: Ruby equivalent of PHP trim()
text = " hello world "
clean = text.strip
puts clean
# hello world
Use strip when you want to remove whitespace only from the beginning and end.
Example 2: Remove only leading whitespace
text = " hello"
puts text.lstrip
# hello
Example 3: Remove only trailing whitespace
text = "hello "
puts text.rstrip
# hello
Example 4: Remove all whitespace everywhere
text = " hello world "
puts text.gsub(/\s+/, "")
# helloworld
This removes spaces, tabs, and newlines throughout the string.
Example 5: Modify the original string in place
Ruby also has destructive versions with !:
text = " hello "
text.strip!
puts text
# hello
Similar methods exist for lstrip! and rstrip!.
Use destructive methods carefully because they change the original object.
Step by Step Execution
Consider this code:
text = " Ruby Basics "
result = text.strip
puts text
puts result
Step 1
text = " Ruby Basics "
The variable text stores a string with spaces before and after the words.
Step 2
result = text.strip
Ruby creates a new string with leading and trailing whitespace removed.
- Original:
" Ruby Basics " - New value:
"Ruby Basics"
The original text is unchanged because strip is non-destructive.
Step 3
puts text
This prints:
Ruby Basics
The spaces are still there in the original string.
Step 4
puts result
This prints:
Ruby Basics
Important takeaway
stripreturns a cleaned copystrip!changes the original string directly
Example:
text = " Ruby Basics "
text.strip!
puts text
# Ruby Basics
Real World Use Cases
Cleaning form input
Users often type extra spaces before or after names, emails, or search terms.
email = params[:email].strip
Validating login data
A password field may need exact handling, but usernames and emails often need trimming first.
username = input_username.strip
Normalizing CSV or file data
Imported files often contain inconsistent spacing.
columns = line.split(",").map(&:strip)
Comparing user input safely
if user_input.strip == "yes"
puts "Confirmed"
end
Without trimming, " yes " would not match.
Cleaning API values
Some external systems return padded values.
status = api_response["status"].strip
Removing all whitespace for formatting rules
Sometimes IDs or codes should contain no spaces at all.
code = raw_code.gsub(/\s+/, "")
Real Codebase Usage
In real Ruby projects, whitespace removal is usually part of input normalization.
Common patterns
Guard clauses before processing
return if name.nil?
name = name.strip
This prevents errors when a value might be nil.
Normalizing arrays of strings
tags = params[:tags].split(",").map(&:strip)
This is common when parsing comma-separated input.
Validation before saving to a database
user.email = params[:email].strip.downcase
Developers often combine trimming with other cleanup steps.
Rejecting empty values after trimming
name = params[:name]&.strip
if name.nil? || name.empty?
puts "Name is required"
end
This avoids treating a string like " " as valid input.
Cleaning lines from files
File.readlines("data.txt").map(&:strip)
Useful when each line has a trailing newline.
Good practice
- Trim inputs close to where they enter the system
- Be careful with destructive methods like
strip! - Decide whether you want to remove edge whitespace or all whitespace
- Handle
nilsafely when input may be missing
Common Mistakes
Mistake 1: Using strip when you want to remove all spaces
text = " hello world "
puts text.strip
# => "hello world"
This keeps the space between hello and world.
If you want to remove all whitespace:
puts text.gsub(/\s+/, "")
# => "helloworld"
Mistake 2: Forgetting that strip returns a new string
text = " hello "
text.strip
puts text
# => " hello "
Fix it by assigning the result:
text = text.strip
Or use:
text.strip!
Mistake 3: Calling strip on nil
Broken example:
name = nil
name.strip
This raises an error because nil does not have a strip method.
Safer version:
name = nil
clean_name = name&.strip
Mistake 4: Using destructive methods without realizing it
text = " hello "
alias_text = text
text.strip!
puts alias_text
# => "hello"
Both variables refer to the same object, so the change affects both references.
Mistake 5: Assuming only spaces are removed
Ruby whitespace methods handle more than plain spaces. They can also affect tabs and newlines.
text = "\n\thello\t\n"
puts text.strip
# => "hello"
Comparisons
| Method | What it removes | Changes original string? | Similar PHP idea |
|---|---|---|---|
strip | Leading and trailing whitespace | No | trim() |
strip! | Leading and trailing whitespace | Yes | trim() with reassignment effect |
lstrip | Leading whitespace only | No | ltrim() |
rstrip | Trailing whitespace only | No | rtrim() |
gsub(/\s+/, "") | All whitespace in the string | No | global regex replacement |
strip vs gsub
text = " hello world "
puts text.strip
# => "hello world"
puts text.gsub(/\s+/, "")
# => "helloworld"
- Use
stripto clean the edges - Use
gsubto remove whitespace everywhere
strip vs strip!
text = " hello "
clean = text.strip # returns new string
text.strip! # changes original string
Choose strip when you want safer, predictable code.
Choose strip! when you intentionally want in-place modification.
Cheat Sheet
# Remove whitespace from both ends
text.strip
# Remove whitespace from the left only
text.lstrip
# Remove whitespace from the right only
text.rstrip
# Remove all whitespace everywhere
text.gsub(/\s+/, "")
# Destructive versions
text.strip!
text.lstrip!
text.rstrip!
Quick rules
stripis Ruby's closest equivalent to PHPtrim()stripremoves whitespace only at the beginning and endgsub(/\s+/, "")removes all whitespace characters- Methods ending with
!modify the original string - Use safe navigation if the value may be
nil
name&.strip
Common choices
- Clean user input:
strip - Parse comma-separated items:
split(",").map(&:strip) - Remove all spaces/tabs/newlines:
gsub(/\s+/, "") - Keep original value unchanged: non-
!method
FAQ
What is the Ruby equivalent of PHP trim()?
Use strip. It removes whitespace from the beginning and end of a string.
How do I remove all spaces from a Ruby string?
If you mean all whitespace everywhere, use:
text.gsub(/\s+/, "")
Does strip remove spaces in the middle of a string?
No. strip only removes leading and trailing whitespace.
What is the difference between strip and strip! in Ruby?
strip returns a new string. strip! modifies the original string.
How do I remove only leading or trailing whitespace in Ruby?
Use lstrip for leading whitespace and rstrip for trailing whitespace.
Does Ruby strip remove tabs and newlines too?
Yes. It removes surrounding whitespace characters, not just regular spaces.
What happens if I call strip on nil?
You get an error. Use safe navigation if needed:
value&.strip
Mini Project
Description
Build a small Ruby input cleaner for user profile data. This project demonstrates the difference between trimming whitespace at the edges and removing whitespace entirely when needed. It reflects a common real-world task: cleaning values before validation or storage.
Goal
Create a Ruby script that cleans several user inputs by trimming names and emails, splitting tags, and removing all whitespace from a referral code.
Requirements
- Create variables for a name, email, tags string, and referral code.
- Trim leading and trailing whitespace from the name and email.
- Split a comma-separated tags string into an array and trim each tag.
- Remove all whitespace from the referral code.
- Print the cleaned results clearly.
Keep learning
Related questions
Add a Default Value to an Existing Column in a Rails Migration
Learn how to add or change a default value on an existing database column using Rails Active Record migrations safely.
Calling a Class Method from an Instance in Ruby
Learn how to call a class method from an instance in Ruby using self.class, with examples, pitfalls, and practical usage patterns.
Calling an Overridden Monkey-Patched Method in Ruby
Learn how to call the original method when monkey patching in Ruby, including alias_method patterns, examples, pitfalls, and practical usage.