0
0
Rubyprogramming~5 mins

Gsub with regex in Ruby

Choose your learning style9 modes available
Introduction

We use gsub with regex to find and replace patterns in text easily.

When you want to replace all phone numbers in a text with a placeholder.
When cleaning up user input by removing unwanted characters.
When formatting dates or codes in a string.
When censoring certain words in a message.
When changing all email addresses in a document to a generic text.
Syntax
Ruby
string.gsub(/pattern/, 'replacement')

The /pattern/ is a regular expression that matches parts of the string.

gsub replaces all matches, not just the first one.

Examples
Replaces every digit with an asterisk.
Ruby
"hello 123".gsub(/\d/, '*')
Replaces all occurrences of "apple" with "orange".
Ruby
"apple banana apple".gsub(/apple/, 'orange')
Removes all lowercase letters, leaving only digits.
Ruby
"abc123xyz".gsub(/[a-z]/, '')
Sample Program

This program replaces all phone numbers in the text with "[phone]".

Ruby
text = "Call me at 123-456-7890 or 987-654-3210."
cleaned = text.gsub(/\d{3}-\d{3}-\d{4}/, "[phone]")
puts cleaned
OutputSuccess
Important Notes

Regex patterns let you match complex text shapes, not just fixed words.

Remember to escape special characters in regex if you want to match them literally.

gsub returns a new string; it does not change the original string unless you use gsub!.

Summary

gsub with regex helps replace all matching parts in a string.

It is useful for cleaning, formatting, or censoring text.

Always test your regex to make sure it matches what you want.