how to gsub in ruby?
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:
Let’s say that we want to replace the word “white” with the word “dark”.
Here’s how:
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.
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:
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:
Which results in:
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.
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:
We find the animal with \w+, which means “one or more alphanumeric characters”.
Then:
This kind of logic isn’t possible with a static value, gsub’s 2nd parameter.
If you have a list of substitutions to make you can use a hash.
Like this one:
This works like a translation dictionary, where the keys will be replaced by their values.
Here’s an example:
Which results in:
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”.
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:
Now it’s your turn to practice with this method so you can make your new knowledge stick.
Thanks for reading 🙂
More Questions
- What is amazon glue crawler?
- What is the dr good santa clarita?
- Amazon alexa ppt?
- How to install fnf mods on mac?
- How to identify srp pistons?
- What is the purpose of toner in skincare?
- Uci when is financial aid disbursed?
- What is the other name of beauty?
- What is diabetes uk helpline?
- Which is best urologist in Hawaii?