- Comprehensive Ruby Programming
- Jordan Hudgens
- 143字
- 2021-07-02 21:13:27
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, the output 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 str variable now has the "The slow brown fox jumped over the slow dog" value:

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.