How to Use the Ruby gsub Method

09/23/2021

Contents

In this article, you will learn how to use the Ruby gsub method.

Using the gsub method

The Ruby gsub method is a powerful tool for replacing text in a string. It stands for “global substitution,” meaning that it can replace all instances of a pattern in a string. The method takes two arguments: a pattern to search for and a replacement string.

The basic syntax of gsub is as follows:

string.gsub(pattern, replacement)

Here, string is the original string you want to modify, pattern is the regular expression or string pattern you want to search for, and replacement is the new string you want to replace pattern with.

For example, consider the following string:

str = "The quick brown fox jumps over the lazy dog"

If we want to replace all occurrences of the letter “o” with the letter “a”, we can use gsub like this:

new_str = str.gsub("o", "a")
puts new_str

Output:

The quick brawn fax jumps aver the lazy dag

Here, the gsub method replaces all occurrences of “o” with “a” in the original string, resulting in the modified string “The quick brawn fax jumps aver the lazy dag”.

Note that the gsub method returns a new string with the replacements made, leaving the original string unchanged. If you want to modify the original string, you can use the destructive version of the method, gsub!:

str.gsub!("o", "a")
puts str

Output:

The quick brawn fax jumps aver the lazy dag

In addition to simple string replacements, gsub can also accept regular expressions as patterns, allowing for more complex replacements. For example, let’s say we want to replace all occurrences of a word that starts with a capital letter with the word “NAME”:

str = "The quick brown Fox jumps over the lazy Dog"
new_str = str.gsub(/\b[A-Z]\w*/, "NAME")
puts new_str

Output:

NAME quick brown NAME jumps over the lazy NAME

Here, the pattern \b[A-Z]\w* matches any word that starts with a capital letter, and the gsub method replaces all matches with the word “NAME”.