tags:

views:

30

answers:

1

I'm attempting to use String#gsub to add a slash in front of % or ?, which i'll then be using in a LIKE query. I'm getting some odd behaviour which hopefully someone can explain:

irb(main):018:0> "%?".gsub(/([%\?])/, '\1')
=> "%?"
irb(main):019:0> "%?".gsub(/([%\?])/, '\\1')
=> "%?"
irb(main):020:0> "%?".gsub(/([%\?])/, '\\\1')
=> "\\1\\1"
irb(main):021:0> "%?".gsub(/([%\?])/, '\\\\1')
=> "\\1\\1"

I've worked around this for the moment by just doing two separate gsubs using strings, but i'd quite like to know if anyone can explain what's going on!

+2  A: 

You stopped one short of your goal :)

>> '%?'.gsub(/([%\?])/, '\\\\\1')
=> "\\%\\?"

Single-quoted strings in Ruby do not accept escape characters, so '\1' and '\\1' are parsed the same, as are '\\\1' and '\\\\1'. You want to pass gsub an argument of \\\1 (three backslashes), so it takes five (really six) literal backslashes to write that as a string literal.

This is probably a case where using double-quoted strings is less prone to error.

jleedev