Reputation: 2096
Try the following code:
s = '#value#'
puts s.gsub('#value#', Regexp.escape('*')) # => '\*'
puts s.gsub('#value#', Regexp.escape('+')) # => ''
Wtf? It looks like the char '\+' (returned by Regexp.escape) is completely ignored by gsub. How to fix this?
Upvotes: 3
Views: 151
Reputation: 1833
It's because of the interpolation of special variables. \+
will be replaced with "the text matched by the highest-numbered capturing group that actually participated in the match" (See the Special Variables section on http://www.regular-expressions.info/ruby.html)
The block syntax is in fact a fix for this, well done.
Upvotes: 3
Reputation: 2096
xsdg of #ruby worked this out
Looks like that gsub's replacement is parsed, so the + is lost somewhere in the process. A workaround is using gsub's block syntax. This way:
s = '#value#'
puts s.gsub('#value#') { |v| Regexp.escape('+') } # => '+'
Works as expected :)
Thanks, xsdg!
Upvotes: 1