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:
The gsub
method is declared as follows:
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. Regexp
a Regexp holds a regular expression, used to match a pattern against strings
The gsub
method returns the copy of the string which contains the replacement
substituted with the pattern.
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 1puts "Hello".gsub(/[aeiou]/, "*")# Example 2puts "Good Morning".gsub(/[ning]/,"<>")
Free Resources