I need to parse and replace text using gsub and a regular expression. A simplified example appears below where I’m saving one of the captured groups — \3 — for use in my replacement string.
my_map.gsub(/(\shref=)(\")(\d+), ' href="/created_path/' + '\3' + '" ' + ' title="' + AnotherObject.find('\3')'"')
In the first use of the captured value, I’m simply displaying it to build the new path. In the second example, I am calling a find with the captured value. The second example will not work.
I’ve tried various ways of escaping the value (“\3″, ”\3”, etc) and even built a method to test displaying the value (works) or using the value in a method (doesn’t work).
Any advice is appreciated.
Use the block form of
gsuband replace your\3references with$3globals:I also switched to
%Q{}for quoting to avoid the confusing quote mixing and concatenation.The second argument in the replacement-string form of
gsub(i.e. the version ofgsubthat you’re trying to use) will be evaluated and concatenated beforegsubis called and **before **the\3value is available so it won’t work.As an aside, is there a method you should be calling on what
AnotherObject.find($3)returns?