- 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":

- 程序員修煉之道:程序設(shè)計入門30講
- Spring技術(shù)內(nèi)幕:深入解析Spring架構(gòu)與設(shè)計
- Visual Basic 6.0程序設(shè)計計算機(jī)組裝與維修
- 編寫高質(zhì)量代碼:改善C程序代碼的125個建議
- R的極客理想:工具篇
- Unity Shader入門精要
- 鋒利的SQL(第2版)
- Visual Basic學(xué)習(xí)手冊
- PLC編程與調(diào)試技術(shù)(松下系列)
- 單片機(jī)C語言程序設(shè)計實訓(xùn)100例
- C++寶典
- Scala編程實戰(zhàn)
- Oracle實用教程
- C++程序設(shè)計教程
- R的極客理想:量化投資篇