William Carpin wrote:
Okay, given the following string:
"This is Will's string!"
what I'm trying to do is replace the single-tick "'" character with a backslash/single-tick "\'", so I can use use that string in a sql query.
To do this in Perl, you'd do the following:
myString =~ s/\'//g;
..which doesn't work in Ruby.
I also tried using the gsub function, with "\\\'" passed in as the second parameter, and it just started outputting some sort sort of goofiness with characters replaced by sub-elements of the string for which I was calling the function on and the like.
I scoured Google for awhile but didn't find anything. Any ideas?
This comes up from time to time. The crucial bit is to understand the levels of quoting / interpretation involved. Here is a general escaping piece:
irb(main):017:0> puts "This is Will's string!".gsub(/'/, '\\\\\\&')
This is Will\'s string!
=> nil
Explanation:
1. level is the string interpretation. You need to escape a backslash to have him literally in a string:
irb(main):019:0> puts '\\'
\
=> nil
2. the RX engine uses backslash as escape character as well, for example to reference groups with \1
So you need four (4) backslashes to make the RX engine insert a single backslash:
irb(main):020:0> puts "This is Will's string!".gsub(/'/, '\\\\')
This is Will\s string!
=> nil
3. the RX engine uses \& as a placeholder for the match:
irb(main):022:0> puts "This is Will's string!".gsub(/'/, '<\\&>')
This is Will<'>s string!
=> nil
Combined makes 3 * 2 = 6 backslashes.
Bonus reply: although the block form is easier on the eye it is actually less performant because the block has to be evaluated for every match. This is rather intended for replacements that are not static, i.e. where the replacement depends in a way on the match that cannot be expressed with the usual mechanisms in the replacement string. For example:
irb(main):023:0> c=0; puts "This is Will's string!".gsub(/i/) { c+= 1 }
Th1s 2s W3ll's str4ng!
=> nil
Kind regards
robert