Section 2.14. Searching a String


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.




The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net