DEV Community

Thieu Luu
Thieu Luu

Posted on

The .gsub method

What is .gsub method?
The .gsub method is used for string manipulation, specifically for replacing occurrences of a specified pattern with another string. The .gsub stands for Global Substitution.

Example:

original_string = "Hello, world! Hello, Ruby!"

# Using .gsub to replace "Hello" with "Hi"
modified_string = original_string.gsub("Hello", "Hi")

puts modified_string
# Output: Hi, world! Hi, Ruby!
Enter fullscreen mode Exit fullscreen mode

The gsub method takes two arguments:
1) The substring or regular expression you want to search for.
2) The replacement string that will replace the matched patterns.

How and when to use .gsub method?
You might use the .gsub method when you need to perform global replacement within a string. Common use cases include cleaning up or transforming data, modifying text content, or implementing search and replace functionality.

Top comments (0)