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. ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.