官术网_书友最值得收藏!

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

主站蜘蛛池模板: 开化县| 武川县| 榆树市| 广水市| 眉山市| 科技| 安新县| 时尚| 印江| 喀什市| 松桃| 侯马市| 新晃| 甘孜县| 郎溪县| 渭源县| 策勒县| 杭锦后旗| 陈巴尔虎旗| 泰来县| 调兵山市| 堆龙德庆县| 高平市| 广宗县| 富宁县| 杭锦旗| 绥芬河市| 新田县| 共和县| 汉阴县| 汝南县| 肥东县| 绥滨县| 杂多县| 赤壁市| 遵化市| 富平县| 民权县| 调兵山市| 洞口县| 古交市|