A collection of computer systems and programming tips that you may find useful.
 
Brought to you by Craic Computing LLC, a bioinformatics consulting company.

Thursday, August 9, 2012

Variable substitution in Ruby sub/gsub replacement strings

With the sub and gsub methods in Ruby you can extract components of the matching string and use them in the replacement string.

For example, with input string 'Hello World' this replacement:
mystring.sub(/(Wo)rld/, '\1bble') -> Hello Wobble
Note the single quotes - if you use double quotes this happens:
mystring.sub(/(Wo)rld/, "\1bble") -> Hello \u0001bble
You can use double quotes if you double escape the 'sequence' \1
mystring.sub(/(Wo)rld/, "\\1bble") -> Hello Wobble
This is very important if you want to include a ruby variable in the replacement string
s = "Mr."
mystring.sub(/(Wo)rld/, "#{s} \\1bble") -> Hello Mr. Wobble
Just remember 'double quotes' means 'double escapes'....

No comments:

Archive of Tips