- Read Tutorial
- Watch Guide Video
In this lesson, we'll walk through a practical string method that enables you to substitute string values that I use in many real-world applications.
str = "The quick brown fox jumped over the quick dog"
If you notice, I've modified this sentence a bit to have the word quick
appear twice in my sentence.
Now, if I want to substitute it with the word slow
I can use the sub
method (which is short for substitution):
str = "The quick brown fox jumped over the quick dog" str.sub "quick", "slow"
In the above code, I'm calling the method sub
on my string variable str
, and passing two argument to the sub
method:
- The first is the word the program has to find
- The second is the replacement word
If I run this code my output will be: The slow brown fox jumped over the quick dog
.
If you notice, this method changes only the first occurrence of the search word quick
and replaces it with slow
.
To change all of the occurrences, we need to use the method gsub
, which stands for global substitution. So, the code should be update like this:
p str.gsub "quick", "slow"
If you run this code, the output would be The slow brown fox jumped over the slow dog
.
Adding a bang
Now I'm going to show you the difference between gsub
and gsub!
.
Going back to the program, if you print the str
variable out after running through the substitution process, it will still be The quick brown fox jumped over the quick dog
because the gsub
method did not change the variable. On the other hand, if you use gsub!
, and then print the value of str
, you can see that the variable str
now has the value The slow brown fox jumped over the slow dog
.
This gsub!
call can be particularly useful when you want to permanently change the value of the variable. However, you need to be careful, especially when working with legacy systems because you don't want to accidentally make a permanent change to someone else's variable in case they are expecting a specific value.