Let’s talk about Ruby’s gsub
method & how to use it. First, you’ll need a string to play with this method.
Why?
Because the whole point of gsub
is to replace parts of a string.
In fact:
The “sub” in “gsub” stands for “substitute”, and the “g” stands for “global”.
Here is an example string:
str = "white chocolate"
Let’s say that we want to replace the word “white” with the word “dark”.
Here’s how:
str.gsub("white", "dark")
This is saying:
Given the string str
, replace ALL occurrences of the first word (white
) with the second word (dark
).
Which means we get to eat much better chocolate.
Oh wait, it’s just a string.
We can’t eat that! 🙂
Anyway…
Ruby’s gsub
method can do a lot more than simple substitution.
Let’s see a few examples.
Replace Patterns With A Regular Expression
Replacing a single word is fine.
But what if you could replace a pattern?
Like:
A year, an email address, a phone number, etc.
You can!
Here’s an example:
"a1".gsub(/\d/, "2") # "a2"
The first argument is a regular expression, and it’s too much to cover here.
But it’s a pattern-matching language.
In this case, \d
looks for numbers, like the number “1” in “a1”.
You can also do this:
"a1".gsub(/(\w)(\d)/, '\2\1')
Which results in:
"1a"
We switched the order!
This works by using a feature called “capture groups”.
We can use the groups as \1
for the first group, \2
for the second group, etc.
Groups are created with parenthesis.
Advanced Gsub With Blocks
Things get really interesting when you start using gsub with a block.
Why?
Because within a block you can use logic to decide how to replace something.
Instead of using a static value.
For example:
"dog".gsub(/\w+/) { |animal| animal == "dog" ? "cat" : "dog" }
We find the animal with \w+
, which means “one or more alphanumeric characters”.
Then:
- If it’s a “dog”, we replace it with “cat”
- If the word is anything else, we replace it with “dog”
This kind of logic isn’t possible with a static value, gsub’s 2nd parameter.
Replace Multiple Terms With A Hash
If you have a list of substitutions to make you can use a hash.
Like this one:
colors = { "B" => "blue", "G" => "green", "R" => "red" }
This works like a translation dictionary, where the keys will be replaced by their values.
Here’s an example:
"BBBGR".gsub(/\w/, colors)
Which results in:
"bluebluebluegreenred"
Make sure that your 1st argument will match the keys.
In this case, \w
matches individual characters, so it will match “B” then replace it with “blue”.
Summary
You have learned about the gsub method in Ruby! It’s a powerful method that allows you to replace, or substitute characters inside a string.
It has multiple uses:
- Removing invalid characters (by making the 2nd argument an empty string)
- Replacing placeholders & acronyms by their full values
- Using patterns & logic to change a string
Now it’s your turn to practice with this method so you can make your new knowledge stick.
Thanks for reading 🙂
Awesome! Thank you for the wonderful coverage of gsub method. Waiting for your next article 🙂
Thanks for reading 🙂
"BBBGR".gsub(/\w/, c)
should be colors"BBBGR".gsub(/\w/, colors)
You’re right! Thank you, it’s fixed now.
I enjoy reading your posts. In your example:
"BBBGR".gsub(/\w/, c)
did you mean for “c” to be the colors hash? (i.e."BBBGR".gsub(/\w/, colors)
) ?Yes, it should be “colors”, thanks for letting me know! 🙂
"a1".gsub(/\d/, 2)
will throw the error: “TypeError: no implicit conversion of Integer into String”. The method works if you simply insert quotes around ‘2’ in the example code.Yes! Thank you Andrew, I should double check my code examples 🙂
Always excited to read your Articles! Thanks for your effort to make Ruby concepts easier for us.
Thanks for your feedback 🙂