Table of contents
1.
Introduction
2.
gsub Method in Ruby
2.1.
Syntax of gsub Method in Ruby
2.1.1.
Replacement Overload
2.1.2.
Hash Value Overload
2.1.3.
Matching Overload
2.2.
Return Type of gsub Method in Ruby
3.
Implementation of the gsub Method in Ruby
3.1.
Replacing Pattern
3.2.
Ruby
3.3.
LowerCase to UpperCase
3.4.
Ruby
3.5.
Replacing Patterns with Hash Values
3.6.
Ruby
4.
Frequently Asked Questions
4.1.
What is the sub method in Ruby?
4.2.
How the gsub method is different from the sub method in Ruby?
4.3.
Is gsub in Ruby case-sensitive?
4.4.
What if the pattern isn't found in a string?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

gsub in Ruby

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

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.

gsub in Ruby

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”.

gsub Method in Ruby

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.

Implementation of the gsub Method in Ruby

In the section of the article “gsub in Ruby”, the implementation of the gsub method in Ruby will be discussed. Here are some examples of how we can learn to implement the gsub method in Ruby.

Replacing Pattern

In this example, we will replace the pattern with the specified value and use the replacement overload in the gsub method.

  • Ruby

Ruby

str = "I love chess and chess is a board game"
new_str = str.gsub("chess", "ludo")
puts new_str
You can also try this code with Online Ruby Compiler
Run Code

 

Output

Replacing Pattern - output


Explanation

In the above code, there is a given string “str”, and this “str” string is used with the method gsub with the arguments ‘chess’ and ‘ludo’ where all the occurrences of ‘chess’ will be replaced with ‘ludo’.

LowerCase to UpperCase

In this example, we will convert all the lowercase words in the string to the uppercase of their equivalent words, where the matching overload will be used in the gsub method in Ruby:

  • Ruby

Ruby

str = "I am a Ninja Coder"
new_str = str.gsub(/\w+/) { |match| match.upcase }
puts new_str
You can also try this code with Online Ruby Compiler
Run Code

 

Output

LowerCase to UpperCase - output


Explanation

In the above code, there is a given string “str”, and this “str” string is used with the method gsub with the arguments ‘w+’ where w represents all the word characters and + represents all the characters match one or more times. In the matching overload, uppercase is passed, converting lower case to upper case.

Replacing Patterns with Hash Values

In this example, we will replace the patterns with their hash values passed in the hash value overload of the gsub method:

  • Ruby

Ruby

str = "Ninja Coder"

new_str = str.gsub(/[iaoe]/, 'i' => '+', 'a' => '#', 'o' => '=', 'e' => '*')

puts new_str
You can also try this code with Online Ruby Compiler
Run Code

 

Output

Replacing Patterns with Hash Values - output

Explanation

In the above code, there is a given string “str”, and this “str” string is used with the method gsub where the first argument is the set of characters including i, a, o, and e. The second argument is the hash values mapping with each character passed in the first argument.

Frequently Asked Questions

What is the sub method in Ruby?

The sub is a method in Ruby that is basically used to replace the first occurrence of the pattern in the string with the specified string in the sub method arguments.

How the gsub method is different from the sub method in Ruby?

In the gsub method, all the occurrences of the pattern in the string with the specified string, and in the sub method, only the first occurrence of the pattern will be replaced.

Is gsub in Ruby case-sensitive?

Yes, the gsub method while calling in Ruby is case-sensitive by default, and the regular expression in the argument of the gsub method can be made a case-sensitive string in Ruby.

What if the pattern isn't found in a string?

If the pattern isn't found in the string, the gsub method in Ruby will return a copy of the original string without any modifications, and no replacements will be made.

Conclusion

The gsub method in Ruby is a built-in method that is basically used to replace all the occurrences of a pattern with the specified string, which returns a new string. The gsub method in Ruby has three overloads: a replacement, hash value, and matching overload.

In the article “gsub in Ruby”, we discussed the gsub method in Ruby with its syntax, parameters, return type, and implementation of the gsub method. Here are more articles that are recommended to read:

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMS, and System Design, etc. as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Happy Learning!

Live masterclass