ruby – Regexp.escape adds weird escapes to a plain space

I stumbled over this problem using the following simplified example:

line = searchstring.dup
line.gsub!(Regexp.escape(searchstring)) { '' }

My understanding was, that for every String stored in searchstring, the gsub! would cause that line is afterwards empty. Indeed, this is the case for many strings, but not for this case:

searchstring =  "D "
line = searchstring.dup
line.gsub!(Regexp.escape(searchstring)) { '' }
p line

It turns out, that line is printed as "D " afterwards, i.e. no replacement had been performed.

This happens to any searchstring containing a space. Indeed, if I do a

p(Regexp.escape(searchstring))

for my example, I see "D\\ " being printed, while I would expect to get "D " instead. Is this a bug in the Ruby core library, or did I misuse the escape function?

Some background: In my concrete application, where this simplified example is derived from, I just want to do a literal string replacement inside a long string, in the following way:

REPLACEMENTS.each do
  |from, to|
  line.chomp!
  line.gsub!(Regexp.escape(from)) { to }      
end

. I’m using Regexp.escape just as a safety measure in the case that the string being replaced contains some regex metacharacter.

I’m using the Cygwin port of MRI Ruby 2.6.4.

Read more here: Source link