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.
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 :
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
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.
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
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:
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() |
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 on ?
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
How to Call Shell Commands from Ruby and Capture Output
Learn how to run shell commands in Ruby, capture output, check exit status, and choose the right method for scripts and apps.
How to Check Whether a String Contains a Substring in Ruby
Learn how to check if a string contains a substring in Ruby using include?, match, and multiline string examples.
How to Check if a Hash Key Exists in Ruby
Learn how to check whether a specific key exists in a Ruby hash using key?, has_key?, and include? with clear examples.