- Comprehensive Ruby Programming
- Jordan Hudgens
- 217字
- 2021-07-02 21:13:27
String substitution guide
In this section, 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 quick word appear twice in my sentence.
Now, if I want to substitute it with the slow word, 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 preceding code, I'm calling the sub method on my str string variable and passing two arguments 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 quick search word and replaces it with slow.
To change all of the occurrences, we need to use the gsub method, which stands for global substitution. So, the code should be updated 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":

- 軟件安全技術
- Advanced Machine Learning with Python
- Objective-C應用開發全程實錄
- Flink SQL與DataStream入門、進階與實戰
- Java性能權威指南(第2版)
- TypeScript項目開發實戰
- Learning Salesforce Einstein
- Visual FoxPro程序設計習題集及實驗指導(第四版)
- Visual Basic程序設計基礎
- 例解Python:Python編程快速入門踐行指南
- 前端架構設計
- Android開發進階實戰:拓展與提升
- 趣學數據結構
- Learning IBM Bluemix
- R High Performance Programming