1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Using Strings

By

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.

#!/usr/bin/env ruby

# Original string
s = "My hovercraft is full of eels"
puts s

s.sub!(/hovercraft/, 'spaceship')
s.sub!(/eels/, 'tribbles')

# \w means "word character", \w+ means
# a sequence of word characters. In short,
# \w+ will match words separated by spaces.
s.gsub!(/\w+/) do|w|
  w.capitalize
end

# Transformed string
puts s
  1. About.com
  2. Technology
  3. Ruby
  4. Beginning Ruby
  5. Substitutions Using Regular Expressions

©2014 About.com. All rights reserved.