What if you could fix every typo in your text with just one simple command?
Why Gsub and sub for replacement in Ruby? - Purpose & Use Cases
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!
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.
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.
text = "Hello world! Hello everyone!" # Manually replace 'Hello' with 'Hi' by checking each word
text = "Hello world! Hello everyone!" text = text.gsub('Hello', 'Hi') # Replaces all 'Hello' with 'Hi'
This lets you quickly and safely update text, making your programs smarter and your work easier.
Imagine fixing a typo in thousands of emails or changing a product name in all your website pages instantly.
sub replaces the first found match in a string.
gsub replaces all matches throughout the string.
Both help automate text changes quickly and accurately.