October 2006
Intermediate to advanced
888 pages
16h 55m
English
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. ...
Read now
Unlock full access