Question

How to Replace a Word in a String in Ruby

rubyruby-on-rails-3

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 occurrence
  • gsub — 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.

  • sub is like using correction fluid on the first matching word you see.
  • gsub is 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.

Take Quiz

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:

My name is John

The ! version changes the original string, while the non-! version returns a new string.

Step by Step Execution

Consider this example:

sentence = "My name is Robert"
result = sentence.sub("Robert", "John")

puts sentence
puts result

Step by step

  1. sentence is assigned the value:

    "My name is Robert"
    
  2. Ruby evaluates:

    sentence.sub("Robert", "John")
    
  3. Ruby looks for the first occurrence of "Robert" inside the string.

  4. It finds a match and creates a new string where "Robert" is replaced by "John".

  5. That new string is stored in result.

  6. puts sentence prints the original string:

    My name is Robert
    
  7. puts result prints the new string:

    My name is John
    

Important detail

sub does not change sentence unless you use sub!.

sentence = "My name is Robert"
sentence.sub("Robert", "John")

puts sentence

Output:

My name is Robert

This surprises many beginners.

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!
Take Quiz

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:

John and Robert

Fix: use gsub.

puts sentence.gsub("Robert", "John")

3. Matching the wrong capitalization

sentence = "My name is robert"
puts sentence.sub("Robert", "John")

No replacement happens because Robert and robert are different.

Fix: match the exact text, or use a regular expression if needed.

4. Replacing part of a larger word by accident

text = "Roberto is here"
puts text.sub("Robert", "John")

This can produce unexpected results if the target appears inside another word.

If you need whole-word matching only, use a regular expression with word boundaries:

text = "Robert Roberto Robert"
puts text.gsub(/\bRobert\b/, "John")

Output:

John Roberto John

5. Confusing variable naming conventions

Ruby variable names usually use snake_case:

copy_sentence = "My name is Robert"

This is preferred over:

Copysentence = "My name is Robert"

A name starting with a capital letter looks like a constant in Ruby.

Comparisons

Here is a quick comparison of the main replacement choices in Ruby:

MethodReplacesChanges original string?Typical use
subFirst match onlyNoReplace one occurrence
sub!First match onlyYesReplace one occurrence in-place
gsubAll matchesNoReplace every occurrence
gsub!All matchesYesReplace every occurrence in-place

sub vs gsub

text = "Robert Robert Robert"

puts text.sub("Robert", "John")
puts text.gsub("Robert", "John")

Output:

John Robert Robert
John John John

Plain string match vs regular expression

ApproachExampleBest for
Plain stringsub("Robert", "John")Exact text replacement
Regular expressiongsub(/\bRobert\b/, "John")Pattern-based replacement

If your task is simple, start with plain strings. Use regular expressions only when you need pattern matching.

Take Quiz

Cheat Sheet

Quick syntax

string.sub("old", "new")
string.gsub("old", "new")
string.sub!("old", "new")
string.gsub!("old", "new")

Rules

  • sub replaces the first match only
  • gsub replaces 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"

Whole-word replacement

"Robert Roberto".gsub(/\bRobert\b/, "John")
# => "John Roberto"

Beginner tip

If you only want to replace one word in a sentence once, use:

sentence.sub("old_word", "new_word")

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 sub instead of gsub

Can I replace only a whole word and not part of another word?

Yes. Use a regular expression with word boundaries:

text.gsub(/\bRobert\b/, "John")

Should I use a loop to replace words in a string?

Usually no. Ruby's built-in methods like sub and gsub are simpler and clearer for this task.

Take Quiz

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.
Take Quiz

Keep learning

Related questions

View more