Introduction
In Ruby, there is a method called “sub” that is used to replace the first occurrence of the pattern in the string. But what if we want to replace all the occurrences of the pattern? Then there is another method in Ruby called “gsub”, which can replace all the occurrences of the pattern occurrences.

In the article “gsub in Ruby”, we will discuss what is the gsub method in Ruby with its syntax, parameters, return type, and the main part, which is the implementation of gsub in Ruby.
gsub Method in Ruby
In the article “gsub in Ruby”, we will discuss what is the gsub method in Ruby. The gsub is a method in Ruby that replaces all the pattern occurrences with the specified value. For example, if the string is “I love chess”, the pattern is “chess”, and the specified value by which the pattern will be changed is “football”. Then the gsub method will return a new string where the content will be “I love football”.

Syntax of gsub Method in Ruby
There are a total of three overloads that can be used in the gsub method. Here is the syntax of all three overloads of the gsub in ruby:
Replacement Overload
Here is the syntax of the gsub in Ruby with replacement overload:
str.gsub(pattern, replacement) ⇒ String
In the above syntax, there are two mandatory parameters: the first is the pattern that will be changed, and the second is the value by which the pattern will be replaced.
Hash Value Overload
Here is the syntax of the gsub in Ruby with hash value overload:
str.gsub(pattern, hash) ⇒ String
In the above syntax, there are two mandatory parameters. The first parameter is the regular expression, and the second parameter will accept the block of code that generates replacement text dynamically based on the match.
Matching Overload
Here is the syntax of the gsub in Ruby with matching overload:
str.gsub(pattern) {|match| ... } ⇒ String
In the above syntax, there are two mandatory parameters. So the first parameter is the regular expression, and the second parameter will accept the block of code that allows to generate replacement text dynamically based on the match.
Return Type of gsub Method in Ruby
The gsub method returns a new string after replacing all the occurrences of the pattern with the specified string, and the original string will not be changed.