Ruby Methods: String#gsub

Melissa Brown
Launch School
Published in
2 min readApr 29, 2018

The gsub string method is a substitution method, much like the old word document find and replace tool. It finds all instances of the matched string and replaces it with the new argument.

The method takes two arguments. The first is the text you want to replace and the second is the new text.

You can also use it with regular expression if you need more flexibility. For example, if you wanted to replace any number in a string rather than a specific number.

Where gsub gets really interesting is when you use it with blocks.Let’s say there was a 20 percent discount on all items.

Gsub also accepts a hash as a second argument.

What if we wanted to replace different words in a sentence with different values and leave the rest of the sentence in tact. Again the hash comes in handy. Let’s say I want to upgrade everyone’s membership level. All those who were Silver Members are now Gold Members and all those who were Bronze Members are now Silver Members.

Let’s look at how we can do this.

Let’s look at what we are doing here. First, we are using regex to find each word in the sentence. Each word is passed into the block as an argument and set the variable ‘m’. We then call fetch on our collection the membership hash. On each loop, we pass fetch our variable ‘m’ variable (the current word in the sentence) as an argument. If a match is found fetch returns the value for that key. If there is no match then the original word is return. Fetch is a great method to use because we can send it two arguments. If there is no match for the key we return our default value: the ‘m’ variable.

fetch(key [, default] ) → object

There you go some cool ways to use gsub

--

--