Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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

Thanks for reading

The post 3 Awesome Ways To Use Ruby’s Gsub Method appeared first on RubyGuides. Don't miss your free gift here :)



This post first appeared on Black Bytes, please read the originial post: here

Share the post

3 Awesome Ways To Use Ruby’s Gsub Method

×

Subscribe to Black Bytes

Get updates delivered right to your inbox!

Thank you for your subscription

×