4

I'm working in Ruby and I'm trying to escape ' characters to \' so that I can use them in SQL. I'm trying to use gsub, but it doesn't seem to be working.

"this doesn't work".gsub /'/, '\\'' #=> "this doesnt workt work"
"this doesn't work".gsub /'/, '\\\'' #=> "this doesnt workt work"
"this doesn't work".gsub /'/, '\\\\'' #=> "this doesn\\'t work"
"this doesn't work".gsub /'/, '\\\\\'' #=> "this doesn\\'t work"

I don't know if gsub is even the right method to be using, so I'm willing to try almost anything that gets the results I'm looking for.

Kyle Sletten
  • 5,365
  • 2
  • 26
  • 39
  • 2
    Don't stop at four. Go for five. Actually, four should return an error. Also, notice that in order for ruby to show (inspect) the result within double quotation, it will escape a backslash. You might not be noticing that you already got it. – sawa Jun 27 '11 at 22:08
  • @sawa Thanks. You're right, I didn't even notice that I got it right. – Kyle Sletten Jun 27 '11 at 22:15

2 Answers2

3

Someone else had this very issue, due to a special meaning/interpretation in Ruby's regex.

\' means $' which is everything after the match. Escape the \ again and it works

See this answer.

Does this work?

"this doesn't work".gsub /'/, '\\\\\'' => "this doesn\\'t work"
Community
  • 1
  • 1
jefflunt
  • 33,527
  • 7
  • 88
  • 126
  • 1
    The problem with that solution is that it double-escapes the `'` to `\\'`. I'm looking for a `\'`. – Kyle Sletten Jun 27 '11 at 22:05
  • 1
    Dang it. I forgot that when the result is displayed in double quotes it shows it escaped. When the program wrote to a file and I opened it, everything is correct. I guess I'm just an idiot. – Kyle Sletten Jun 27 '11 at 22:14
  • No worries. Threw me off too. So long as the code works, that is the point, yes? ;) – jefflunt Jun 27 '11 at 22:15
0

You must escape the \ and the '. When you need the ' in the result, why not define the result with "

puts "this doesn't work".gsub /'/, "\\\\'" #=> "this doesn\'t work"

\ must be escaped anyway.

knut
  • 27,320
  • 6
  • 84
  • 112