In a Ruby script, I'm using string#gsub
to generate a string that is used as a regex. This regex has to match against a +
character, so I'm using \+
to escape it.
This example code isolates my source of confusion. In this code, the regex I want to create is /a\+b/
. However, when I use #gsub
, the regex that is returned is /ab/
.
string = 'a\+b'
expected = Regexp.new(string)
actual = Regexp.new('x'.gsub('x', string))
# expected returns /a\+b/
# actual returns /ab/
I couldn't find anything in the Ruby documentation about #gsub
and +
characters. Can anybody help me understand what is happening to produce this result?
For now, to make my code work, I'm matching against \x2B
, the ANSI hex code for the +
character. Is there a way to achieve this that isn't so obfuscated?
Thanks in advance!