2

So I think this is weird:

"x'y".gsub("'", "\\'")
=> "xyy" 

The variant,

'x"y'.gsub('"', "\'")
=> "x'y" 

Works just fine.

Either it's a bug (unlikely) or it's something with how Ruby handles backreferences that I don't understand. Can anyone explain what happens in the first case?

Confusion
  • 16,256
  • 8
  • 46
  • 71

1 Answers1

1

\' means $' which is everything after the match.
(or)
\' in a gsub replacement means "part of the string after the match."

Escape the \ again and it works,

"x'y".gsub("'", "\\\\'")

you can also use %q delimiters here,

"x'y".gsub("'", %q(\\\'))  

//(IRB uses \\ to make an escape-\ visible)

Referred from Gsub wierd behaviour

Community
  • 1
  • 1
Sravan
  • 18,467
  • 3
  • 30
  • 54
  • Do you know if this is documented anywhere? The documentation for [sub](http://ruby-doc.org/core-2.3.1/String.html#method-i-gsub) even says `[..] but is actually not a pattern capture group e.g. "\'", then it will have to be preceded by two backslashes like so "\\'"` – Confusion Jul 28 '16 at 13:29
  • Me too didn't get the correct documentation of it any where, but as we need to escape the escape character and single quote so shld use 4 back slashes there. – Sravan Jul 28 '16 at 13:44