What is the gsub method in Ruby?

In Ruby, the gusb method replaces all occurrences of a pattern with a given replacement and returns the copy of the string. For example, if we want to replace all the vowels in a string with asterisks, the result will be as follows:

Syntax

The gsub method is declared as follows:

Parameters

The gsub method takes two parameters:

  • pattern: This is the substring/character set that will be removed.

  • replacement: This is the character(s) that will be substituted for the characters to be removed.

The pattern is typically a Regexpa Regexp holds a regular expression, used to match a pattern against strings.

Return value

The gsub method returns the copy of the string which contains the replacement substituted with the pattern.

Example

The code below shows the use of the gsub method in Ruby. The first example returns the copy of the string with its vowels replaced with asterisks. The second example substitutes the pattern with <> as a replacement:

# Example 1
puts "Hello".gsub(/[aeiou]/, "*")
# Example 2
puts "Good Morning".gsub(/[ning]/,"<>")
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved