What is the easiest way to replace a word in a string in Ruby?

What is the easiest way to replace a word in a string in Ruby?

I have the following string:

sentence = "My name is Robert"

How can I replace a specific word in this sentence without using complex code or a loop? What are the best methods for Ruby string replace operations?

The simplest way to replace a word in Ruby is to use sub. It replaces the first occurrence of a match.

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

This works well when you only need to replace the first occurrence and don’t need to modify the original string.

That’s great if you only need to replace one instance, but if you’re dealing with multiple occurrences of the same word, gsub is better since it replaces all occurrences.

sentence = "Robert is my friend. Robert is nice."
sentence.gsub("Robert", "John")
# => "John is my friend. John is nice."

So if you have a long text and need to replace multiple words, gsub is the way to go.

Those are solid options, but what if the word appears in different cases? You can use gsub with a regex to perform a case-insensitive replacement.

sentence = "My name is robert and ROBERT is my friend."
sentence.gsub(/robert/i, "John")
# => "My name is John and John is my friend."

This makes sure all variations of ‘robert’ get replaced, regardless of capitalization.