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

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved