Thieu Luu
Posted on January 13, 2024
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!
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.
💖 💪 🙅 🚩
Thieu Luu
Posted on January 13, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.