From: "Jesús Gabriel y Galán" Date: 2008-05-29T18:02:51+09:00 Subject: Re: Strings, postgresql and gsub On Thu, May 29, 2008 at 10:47 AM, J-H Johansen wrote: > Hi, > > I'm somewhat stumped at the moment due to problems with inserting > strings in postgresql containing 's. > > Normally, I'd just add a \ to escape the ' and everything would be just fine. > But for some reason, Ruby won't let me do this. > > > ruby 1.8.6 (2007-09-24 patchlevel 111) [i686-linux] > > irb(main):033:0* s = "blah'blah" > => "blah'blah" > irb(main):034:0> s.gsub(/'/, "\\'") > => "blahblahblah" > irb(main):035:0> s.gsub("'", "\\'") > => "blahblahblah" > > > I've seen myself blind on this one ...and I still can't see where the > problem is. Any clues ? This use of gsub processes the escaping of the sub string twice, the Ruby one for the literal string and a second one for backreferences, so you'll need: irb(main):001:0> a = "blah'blah" irb(main):002:0> a.gsub("'", "\\\\'") => "blah\\'blah" irb(main):005:0> a.gsub("'", "\\\\'").length => 10 Hope this helps, Jesus.