0
0
Rubyprogramming~3 mins

Why Gsub and sub for replacement in Ruby? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could fix every typo in your text with just one simple command?

The Scenario

Imagine you have a long letter and you want to change every time a certain word appears. Doing this by reading and rewriting each word by hand would take forever!

The Problem

Manually searching and changing words is slow and easy to mess up. You might miss some words or accidentally change the wrong ones, making your letter confusing.

The Solution

Using sub and gsub in Ruby lets you quickly replace words or parts of text. sub changes the first match, while gsub changes all matches, saving time and avoiding mistakes.

Before vs After
Before
text = "Hello world! Hello everyone!"
# Manually replace 'Hello' with 'Hi' by checking each word
After
text = "Hello world! Hello everyone!"
text = text.gsub('Hello', 'Hi')  # Replaces all 'Hello' with 'Hi'
What It Enables

This lets you quickly and safely update text, making your programs smarter and your work easier.

Real Life Example

Imagine fixing a typo in thousands of emails or changing a product name in all your website pages instantly.

Key Takeaways

sub replaces the first found match in a string.

gsub replaces all matches throughout the string.

Both help automate text changes quickly and accurately.