A fundamental method to search and replace a string is using regular expressions. RegEx is powerful in finding patterns, filtering, and more.
In this guide, we will discuss various ways to manipulate strings in Ruby. We will cover how to perform string substation, insertion, and replacement.
Substring Replacement
The simplest way to replace a string in Ruby is to use the substring replacement. We can specify the string to replace inside a pair of square brackets and set the replace value:
For example:
msg["Ruby"] = "Python"
puts msg
Programming in Python is fun!
In the example above, we used indexing to search and replace a specified string.
If you know the index range of the string you wish to replace, you can specify the index range as:
var1[0..4] = "zello"
puts var1
zello world
In the example, we replace the characters from index 0 to 4, which contains the string “Hello”.
Replace Method
Ruby has a replace method that replaces the entire contents of the specified string with the set contents.
For example:
name.replace "Jane Doe"
puts name
=> Jane Doe
Search and Replace
A typical case when manipulating strings in Ruby is to search and replace a specific string pattern. We can accomplish this by using the built-in sub and gsub method.
These methods accept two arguments: the string to search and the string to replace. They use regular expressions to locate matching patterns and replace all the occurrences of the patterns.
Sub and gsub methods do not modify the source strings. However, you can use the sub! and gsub! to modify the source string.
Example 1
The following is a simple example of sub and gsub methods search and replace.
msg.sub("Ruby", "Python")
=> "Programming in Python is fun!"
puts msg
=> Programming in Ruby is fun!
In the example above, we search for the string “Ruby” and replace it with the string “Python”.
As mentioned, the sub and gsub methods create a new string where you can save the variable:
Programming in Python is fun!
Example 2
The following example illustrates how to use the sub method with a simple regular expression:
var1.sub(/\w+lo/, "hey")
The example above will locate the string ending with lo and replace it with “hey”. Below is an example output:
Example 3
Consider the following example that uppercases a specific word using regex:
var.gsub(/\bhello\b/, "Hello")
Insert String
We can also insert a string into an existing string using the insert method. Take the following example:
msg.insert 5, ","
The index method will take the index position and the value to insert.
Closing
In this quick guide, we discussed various ways to replace a string in Ruby using built-in methods and regular expressions.