Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Ruby Dictionary

  1. Home
  2. Ruby Dictionary
  3. String.sub / gsub

String.sub / gsub

Methods for replacing a specific pattern in a string with another string. sub replaces only the first match, while gsub replaces all matches.

Syntax

# Replaces the first match (returns a new string).
string.sub(pattern, replacement)
string.sub(pattern) { |match| ... }

# Replaces all matches (returns a new string).
string.gsub(pattern, replacement)
string.gsub(pattern) { |match| ... }

# Modifies the original string in place (destructive method).
string.sub!(pattern, replacement)
string.gsub!(pattern, replacement)

Method List

MethodDescription
sub(pattern, str)Returns a new string with the first match replaced. The original string is not modified.
gsub(pattern, str)Returns a new string with all matches replaced. The original string is not modified.
sub!(pattern, str)Modifies the original string in place. Returns the modified string if a replacement was made, or nil if no match was found.
gsub!(pattern, str)Modifies the original string in place, replacing all matches.

Sample Code

sentence = "The cat chased the cat."

# sub replaces only the first match.
puts sentence.sub("cat", "dog")   # The dog chased the cat.

# gsub replaces all matches.
puts sentence.gsub("cat", "dog")  # The dog chased the dog.

# The original string is unchanged.
puts sentence  # The cat chased the cat.

# Replacement using a regular expression.
email = "user@example.com"
puts email.gsub(/@.+/, "@***.***")  # user@***.***

# Using a block to generate the replacement dynamically.
text = "The price is 100 and the quantity is 3."
puts text.gsub(/\d+/) { |n| n.to_i * 2 }  # The price is 200 and the quantity is 6.

# Destructive method modifies the original string.
str = "Hello World"
str.gsub!(" ", "_")
puts str  # Hello_World

Notes

sub and gsub are the fundamental string replacement methods. The first argument can be either a string or a regular expression, allowing for flexible pattern matching. When a block is given, the matched string is passed as an argument and you can generate the replacement dynamically.

The bang versions (sub! and gsub!) modify the original string in place. If no match is found, they return nil, so be careful when chaining the return value.

To search within a string, use include? or index. To convert case, use upcase / downcase.

If you find any errors or copyright issues, please .