A more powerful interface for string manipulation is regular expression substitutions. This method is the most flexible as it can apply to any string. When using the regular expression, you don't need to know the exact location of the substring you want to modify and the string doesn't have to be formatted as a collection of records. As long as you can describe the text you want to change with the regular expression language, you can change it to anything you wish.
There are four primary methods for performing substitutions using regular expressions: sub, sub!, gsub and gsub!. Like their names, these are all variations on the same theme. The sub method will find the first occurance of the regular expression, replace it with the given string and return the new, modified string. If a method ends with the exclamation point in Ruby, likesub!, it means that instead of returning a modified string, the method will act on the string itself. Finally, the gsub family of methods replace all--not just the first-- occurances of a regular expression.
In addition to taking a simple string to perform the replacement, a block may also be used. This is a very powerful interface to the substitution methods. Instead of a single static string, the replacement string can be generated at runtime from the string matched by the regular expression. In the example, a simple call to capitalize is used, but any number of method calls and even further calls to sub or gsub can be used to generate the replacement string.
# Original string
s = "My hovercraft is full of eels"
# \w means "word character", \w+ means
# a sequence of word characters. In short,
# \w+ will match words separated by spaces.
# Transformed string