0
0
Rubyprogramming~5 mins

Gsub and sub for replacement in Ruby

Choose your learning style9 modes available
Introduction

Use sub and gsub to change parts of text by replacing words or characters.

You want to fix a typo in a sentence.
You need to change all spaces to dashes in a string.
You want to replace only the first occurrence of a word.
You want to remove unwanted characters from text.
You want to update a format, like changing dates from slashes to dashes.
Syntax
Ruby
string.sub(pattern, replacement)
string.gsub(pattern, replacement)

sub changes only the first match it finds.

gsub changes all matches in the string.

Examples
Replaces only the first 'l' with 'x'.
Ruby
"hello world".sub("l", "x") #=> "hexlo world"
Replaces all 'l's with 'x'.
Ruby
"hello world".gsub("l", "x") #=> "hexxo worxd"
Changes all slashes to dashes.
Ruby
"2024/06/01".gsub("/", "-") #=> "2024-06-01"
Replaces only the first 'hello' with 'hi'.
Ruby
"hello hello".sub("hello", "hi") #=> "hi hello"
Sample Program

This program shows how sub changes only the first 'apples' to 'oranges', while gsub changes all 'apples' in the text.

Ruby
text = "I love apples and apples are tasty."
first_replace = text.sub("apples", "oranges")
all_replace = text.gsub("apples", "oranges")

puts "Original: #{text}"
puts "After sub: #{first_replace}"
puts "After gsub: #{all_replace}"
OutputSuccess
Important Notes

Both sub and gsub return a new string; they do not change the original string unless you use sub! or gsub!.

You can use strings or regular expressions as the pattern to match.

Remember that sub only replaces the first match it finds.

Summary

sub replaces only the first match in a string.

gsub replaces all matches in a string.

Use these methods to easily change parts of text in Ruby.