0
0
RubyHow-ToBeginner · 3 min read

How to Use sub in Ruby: Replace First Match in String

In Ruby, sub is a method used on strings to replace the first occurrence of a pattern with a specified replacement. You can pass a string or regular expression as the pattern and a replacement string or block to define the new content.
📐

Syntax

The sub method replaces the first match of a pattern in a string with a replacement. The pattern can be a string or a regular expression. The replacement can be a string or a block that returns a string.

  • pattern: The text or regex to find.
  • replacement: The new text to insert instead of the first match.
ruby
string.sub(pattern, replacement)

# or with a block
string.sub(pattern) { |match| replacement }
💻

Example

This example shows how to replace the first occurrence of "cat" with "dog" in a string using sub. It also shows using a block to capitalize the matched word.

ruby
text = "The cat sat on the cat mat."

# Replace first 'cat' with 'dog'
result1 = text.sub("cat", "dog")

# Use regex and block to capitalize first matched word
result2 = text.sub(/cat/) { |match| match.upcase }

puts result1
puts result2
Output
The dog sat on the cat mat. The CAT sat on the cat mat.
⚠️

Common Pitfalls

One common mistake is expecting sub to replace all matches; it only replaces the first one. To replace all, use gsub. Another pitfall is forgetting that sub does not change the original string unless you use sub!.

ruby
text = "hello hello hello"

# Wrong: expecting all replaced
wrong = text.sub("hello", "hi")

# Right: use gsub for all
right = text.gsub("hello", "hi")

puts wrong  # Output: hi hello hello
puts right  # Output: hi hi hi
Output
hi hello hello hi hi hi
📊

Quick Reference

MethodDescriptionModifies Original?
sub(pattern, replacement)Replaces first match with replacementNo
sub!(pattern, replacement)Replaces first match in placeYes
gsub(pattern, replacement)Replaces all matches with replacementNo
gsub!(pattern, replacement)Replaces all matches in placeYes

Key Takeaways

Use sub to replace only the first occurrence of a pattern in a string.
sub accepts a string or regex pattern and a replacement string or block.
To replace all matches, use gsub instead of sub.
sub does not change the original string unless you use sub!.
Blocks with sub let you customize the replacement dynamically.