Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
gsub

What is the gsub method in Ruby?

Umme Ammara

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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

RELATED TAGS

ruby
gsub

CONTRIBUTOR

Umme Ammara
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring