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

gsub and sub

In this page:

  1. gsub and sub

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]/, "*")
🔒

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.