Just like any other programming language, Ruby offers an extensive collection of string manipulation functions. This tutorial aims to demonstrate some of Ruby's basic string manipulation capabilities by showing several different ways of performing a search-and-replace. While some of these examples are not practical approaches to search and replace, they are a great way to demonstrate other string manipulation functions.
In the following example, we use Ruby's ability to select sections of a string as an element of the string's character array. We will select the section "Test" and assign it to the selection "Example"
puts("Replace 'Test' with 'Example, using array sections")
string = "Test, Ruby String Manipulation Test, This is a Test"
puts(string)
string["Test"]="Example"
puts(string)
puts("\n")
Results:
Replace 'Test' with 'Example, using array sections Test, Ruby String Manipulation Test, This is a Test Example, Ruby String Manipulation Test, This is a Test
Notice that this only replaces the first instance of the string "Test". If we want to replace all instances using this same technique, we can use a while loop to repeat the process until all instances have been replaced.
puts("Replace 'Test' with 'Example, using array sections in while loop")
string = "Test, Ruby String Manipulation Test, This is a Test"
while !string["Test"].nil?
string["Test"]="Example"
end
puts(string)
puts("\n")
This will repeat the first example until the string element "Test" is null.
Results:
Replace 'Test' with 'Example, using array sections in while loop Example, Ruby String Manipulation Example, This is a Example
Next we will perform a search and replace using a few string manipulation functions common to all languages. In this example we will use 'index' to find the position of the search string. Combined with 'length' which gives us the length of a string, and the ability to create substrings, we can piece together a new string with all the replacements.
puts("Replace 'Test' with 'Example, using index, length and substrings")
string = "Test, Ruby String Manipulation Test, This is a Test"
search = "Test"
replace = "Example"
while !string["Test"].nil?
pos = string.index(search)
len = search.length
string = string[0, pos] + replace + string[pos+len..-1]
end
puts(string)
puts("\n")
Finally, the most practical method of search and replace, and likely the one you will end up using.
puts("Replace 'Test' with 'Example, using gsub")
string = "Test, Ruby String Manipulation Test, This is a Test"
string = string.gsub("Test","Example")
puts(string)
puts("\n")
gsub is specifically designed for search and replace. The first parameter is the search string, and the second is the replacement string.
You might also be interested in





