- 2.1 Representing Ordinary Strings
- 2.2 Representing Strings with Alternate Notations
- 2.3 Using Here-Documents
- 2.4 Finding the Length of a String
- 2.5 Processing a Line at a Time
- 2.6 Processing a Byte at a Time
- 2.7 Performing Specialized String Comparisons
- 2.8 Tokenizing a String
- 2.9 Formatting a String
- 2.10 Using Strings As IO Objects
- 2.11 Controlling Uppercase and Lowercase
- 2.12 Accessing and Assigning Substrings
- 2.13 Substituting in Strings
- 2.14 Searching a String
- 2.15 Converting Between Characters and ASCII Codes
- 2.16 Implicit and Explicit Conversion
- 2.17 Appending an Item Onto a String
- 2.18 Removing Trailing Newlines and Other Characters
- 2.19 Trimming Whitespace from a String
- 2.20 Repeating Strings
- 2.21 Embedding Expressions Within Strings
- 2.22 Delayed Interpolation of Strings
- 2.23 Parsing Comma-Separated Data
- 2.24 Converting Strings to Numbers (Decimal and Otherwise)
- 2.25 Encoding and Decoding rot13 Text
- 2.26 Encrypting Strings
- 2.27 Compressing Strings
- 2.28 Counting Characters in Strings
- 2.29 Reversing a String
- 2.30 Removing Duplicate Characters
- 2.31 Removing Specific Characters
- 2.32 Printing Special Characters
- 2.33 Generating Successive Strings
- 2.34 Calculating a 32-Bit CRC
- 2.35 Calculating the MD5 Hash of a String
- 2.36 Calculating the Levenshtein Distance Between Two Strings
- 2.37 Encoding and Decoding base64 Strings
- 2.38 Encoding and Decoding Strings (uuencode/uudecode)
- 2.39 Expanding and Compressing Tab Characters
- 2.40 Wrapping Lines of Text
- 2.41 Conclusion
2.13 Substituting in Strings
We've already seen how to perform simple substitutions in strings. The sub and gsub methods provide more advanced pattern-based capabilities. There are also sub! and gsub!, their in-place counterparts.
The sub method substitutes the first occurrence of a pattern with the given substitute-string or the given block:
s1 = "spam, spam, and eggs" s2 = s1.sub(/spam/,"bacon") # "bacon, spam, and eggs" s3 = s2.sub(/(\w+), (\w+),/,'\2, \1,') # "spam, bacon, and eggs" s4 = "Don't forget the spam." s5 = s4.sub(/spam/) { |m| m.reverse } # "Don't forget the maps." s4.sub!(/spam/) { |m| m.reverse } # s4 is now "Don't forget the maps."
As this example shows, the special symbols \1, \2, and so on may be used in a substitute string. However, special variables such as $& (or the English version $MATCH) may not.
If the block form is used, the special variables may be used. However, if all you need is the matched string, it will be passed into the block as a parameter. If it is not needed at all, the parameter can of course be omitted.
The gsub method (global substitution) is essentially the same except that all matches are substituted rather than just the first:
s5 = "alfalfa abracadabra" s6 = s5.gsub(/a[bl]/,"xx") # "xxfxxfa xxracadxxra" s5.gsub!(/[lfdbr]/) { |m| m.upcase + "-" } # s5 is now "aL-F-aL-F-a aB-R-acaD-aB-R-a"
The method Regexp.last_match is essentially identical to $& or $MATCH.