← Back to Ruby Course | Chapter 3: Strings | Lesson 5 of 7

gsub and sub

sub and gsub find a pattern in text and swap it for something else, like Find and Replace in a document. sub changes only the first match, while gsub changes them all.

In this page:

  1. gsub and sub
Syntax
ruby
string.sub(pattern, replacement)
string.gsub(pattern, replacement)

gsub and sub

sub(pattern, replacement) replaces the first match of a pattern in a string, and gsub() replaces every match (global substitute).

Both accept either a literal string or a regular expression as the pattern, and a block form lets you compute the replacement dynamically. Like most Ruby string methods, they return a new string unless you use the ! version (gsub!).

Note: gsub accepts a block form, like text.gsub(/\\d+/) { |n| n.to_i * 2 }, letting you compute each replacement dynamically.

Example: gsub and sub

markup
text = "cat bat cat sat"

puts text.sub("cat", "dog")
puts text.gsub("cat", "dog")
puts text.gsub(/[aeiou]/, "*")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using sub and expecting all matches to change, when only the first does; use gsub.
  2. Expecting text.gsub(...) to change text, when it returns a new string unless you use gsub!.
  3. Using a string as a pattern that contains regex symbols, such as ".", which in a regex matches any character.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.