RubyGuides
Share this post!

3 Awesome Ways To Use Ruby’s Gsub Method

Let’s talk about Ruby’s gsub method.

First, you’ll need a string to play with this method.

Why?

Because you use gsub on a string to replace parts of it.

In fact:

The “sub” in “gsub” stands for “substitute”, and the “g” stands for “global”.

Got your string?

Good.

If not, you can borrow mine.

Here it is:

str = "white chocolate"

Let’s say that we want to replace “white” with “dark”.

Here’s how:

str.gsub("white", "dark")

This is saying:

Given the string str, command it to 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 in here.

But it’s a pattern-matching language.

In this case, \d looks for numbers, like the “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 featured 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

Ruby Gsub Mindmap

Now it’s your turn to practice with this method so you can make your new knowledge stick.

Thanks for reading 🙂

Leave a Comment:

10 comments
Taha Maqbool says a couple of weeks ago

Awesome! Thank you for the wonderful coverage of gsub method. Waiting for your next article 🙂

Reply
    Jesus Castello says a couple of weeks ago

    Thanks for reading 🙂

    Reply
json says a couple of weeks ago

"BBBGR".gsub(/\w/, c) should be colors "BBBGR".gsub(/\w/, colors)

Reply
    Jesus Castello says a couple of weeks ago

    You’re right! Thank you, it’s fixed now.

    Reply
Christopher says a couple of weeks ago

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)) ?

Reply
    Jesus Castello says a couple of weeks ago

    Yes, it should be “colors”, thanks for letting me know! 🙂

    Reply
Andrew Talle says a couple of weeks ago

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

Reply
    Jesus Castello says a couple of weeks ago

    Yes! Thank you Andrew, I should double check my code examples 🙂

    Reply
Kanad says a couple of weeks ago

Always excited to read your Articles! Thanks for your effort to make Ruby concepts easier for us.

Reply
    Jesus Castello says a couple of weeks ago

    Thanks for your feedback 🙂

    Reply
Add Your Reply