Reputation: 493
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.
Upvotes: 0
Views: 442
Reputation: 434945
Use the block form of gsub
and replace your \3
references with $3
globals:
my_map.gsub(/(\shref=)(\")(\d+)/) { %Q{ href="/created_path/#{$3}" title="#{AnotherObject.find($3)"} }
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 of gsub
that you're trying to use) will be evaluated and concatenated before gsub
is called and **before **the \3
value is available so it won't work.
As an aside, is there a method you should be calling on what AnotherObject.find($3)
returns?
Upvotes: 1