Question
I have the following Ruby string:
copy_sentence = "My name is Robert"
How can I replace a single word in this sentence in a simple way, without using complex code or a loop?
Short Answer
By the end of this page, you will understand how to replace text inside a Ruby string using built-in string methods. You will learn when to use sub for one replacement, when to use gsub for all replacements, and how to avoid common beginner mistakes.
Concept
In Ruby, strings come with built-in methods for finding and replacing text. The most common methods are:
sub— replaces the first matching occurrencegsub— replaces all matching occurrences
This matters because text replacement is a very common task in programming. You might need to:
- update a user's name in a message
- clean data before saving it
- change placeholders in templates
- transform text from files or APIs
Instead of writing a loop yourself, Ruby lets you express the task directly with a single method call.
For a sentence like:
"My name is Robert"
if you want to replace Robert with John, Ruby can do that very simply.
A key thing to know is that strings are matched exactly unless you use patterns like regular expressions. So replacing Robert works only if that exact text appears in the string.
Mental Model
Think of a string as a line of printed words on paper.
subis like using correction fluid on the first matching word you see.gsubis like replacing every matching word in the whole sentence.
So if the sentence contains one Robert, sub is enough. If the sentence contains several copies of the same word, gsub changes them all.
Syntax and Examples
Ruby's basic replacement syntax looks like this:
string.sub("old", "new")
string.gsub("old", "new")
Replace one word
sentence = "My name is Robert"
new_sentence = sentence.sub("Robert", "John")
puts new_sentence
Output:
My name is John
Replace all matching words
sentence = "Robert likes apples. Robert likes bananas."
new_sentence = sentence.gsub("Robert", "John")
puts new_sentence
Output:
John likes apples. John likes bananas.
Modify the original string directly
Ruby also provides bang methods:
sentence = "My name is Robert"
sentence.sub!("Robert", "John")
puts sentence
Output:
Step by Step Execution
Consider this example:
sentence = "My name is Robert"
result = sentence.sub("Robert", "John")
puts sentence
puts result
Step by step
-
sentenceis assigned the value:"My name is Robert" -
Ruby evaluates:
sentence.sub("Robert", "John") -
Ruby looks for the first occurrence of
"Robert"inside the string. -
It finds a match and creates a new string where
"Robert"is replaced by"John". -
That new string is stored in
result. -
puts sentenceprints the original string:My name is Robert
Real World Use Cases
Text replacement appears in many practical situations:
- User messages: replace a placeholder like
"NAME"with a real username - Templates: turn
"Hello, {user}"into"Hello, Alice" - Data cleanup: replace outdated labels or terms in imported text
- Log processing: remove or mask sensitive words
- File content updates: change text when reading configuration or document files
Example:
template = "Hello, NAME!"
message = template.sub("NAME", "Alice")
puts message
Output:
Hello, Alice!
Real Codebase Usage
In real Ruby projects, developers often use string replacement in small, focused ways rather than with manual loops.
Common patterns include:
- Template substitution
- Input normalization
- Data sanitization
- Early cleanup before validation
Example: normalize incoming text
name = params[:name].to_s.strip
clean_name = name.gsub(" ", " ")
Example: replace placeholders in generated content
template = "Welcome, {name}!"
message = template.sub("{name}", user.name)
Example: simple masking
log_line = "User email: test@example.com"
masked = log_line.sub("test@example.com", "[FILTERED]")
In larger codebases, developers usually prefer built-in methods like sub and gsub because they are:
- readable
- concise
- tested
- easier to maintain than custom looping code
Common Mistakes
Here are common beginner mistakes when replacing words in Ruby.
1. Expecting sub to change the original string
Broken expectation:
sentence = "My name is Robert"
sentence.sub("Robert", "John")
puts sentence
Output:
My name is Robert
Why: sub returns a new string.
Fix:
sentence = "My name is Robert"
sentence = sentence.sub("Robert", "John")
Or use:
sentence.sub!("Robert", "John")
2. Using sub when you need all matches replaced
sentence = "Robert and Robert"
puts sentence.sub("Robert", "John")
Output:
Comparisons
Here is a quick comparison of the main replacement choices in Ruby:
| Method | Replaces | Changes original string? | Typical use |
|---|---|---|---|
sub | First match only | No | Replace one occurrence |
sub! | First match only | Yes | Replace one occurrence in-place |
gsub | All matches | No | Replace every occurrence |
gsub! | All matches | Yes | Replace every occurrence in-place |
sub vs gsub
Cheat Sheet
Quick syntax
string.sub("old", "new")
string.gsub("old", "new")
string.sub!("old", "new")
string.gsub!("old", "new")
Rules
subreplaces the first match onlygsubreplaces all matches- methods without
!return a new string - methods with
!modify the original string - matching is case-sensitive by default
Examples
"My name is Robert".sub("Robert", "John")
# => "My name is John"
"Robert Robert".gsub("Robert", "John")
# => "John John"
text = "Robert"
text.sub!("Robert", "John")
# text is now "John"
FAQ
How do I replace one word in a Ruby string?
Use sub:
sentence.sub("Robert", "John")
What is the difference between sub and gsub in Ruby?
sub replaces the first match only. gsub replaces every match.
Does sub change the original string in Ruby?
No. It returns a new string. Use sub! if you want to modify the original string.
How do I replace all occurrences of a word in Ruby?
Use gsub:
text.gsub("Robert", "John")
Why is my Ruby replacement not working?
Common reasons include:
- the text does not match exactly
- capitalization is different
- you forgot to save the returned value
- you used
subinstead ofgsub
Mini Project
Description
Build a small Ruby script that personalizes a message by replacing a name inside a sentence. This demonstrates how to use string replacement in a practical way without writing loops.
Goal
Create a Ruby program that replaces a target word in a sentence and prints both the original and updated versions.
Requirements
- Create a string containing a sentence with a person's name.
- Replace one word in the sentence using a Ruby string method.
- Print the original sentence.
- Print the updated sentence.
- Also show how to replace all occurrences in a second example.
Keep learning
Related questions
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.
Convert a Unix Timestamp to Ruby DateTime
Learn how to convert Unix timestamps to Ruby DateTime and Time objects, with examples, differences, pitfalls, and practical Ruby usage.