Glenjamin
Glenjamin

Reputation: 7350

How can i escape database wildcards in ruby?

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!

Upvotes: 0

Views: 207

Answers (1)

Josh Lee
Josh Lee

Reputation: 177675

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.

Upvotes: 2

Related Questions