I want to replace all occurences of a certain character in a string
with a backslash followed by a single quote. Sounds like a trivial
task, but this is what I get:
"this is a test".gsub( "a", "\\'" ) -> "this is test test"
What I want is "this is \' test".
Neither does this work:
"this is a test".gsub( "a", '\' + "'" )
No matter what I am doing, as soon as a backslash is followed by a
single quote in the replacement string, I am getting weird results.
I want to replace all occurences of a certain character in a string
with a backslash followed by a single quote. Sounds like a trivial
task, but this is what I get:
"this is a test".gsub( "a", "\\'" ) -> "this is test test"
What I want is "this is \' test".
Neither does this work:
"this is a test".gsub( "a", '\' + "'" )
No matter what I am doing, as soon as a backslash is followed by a
single quote in the replacement string, I am getting weird results.
On 17 Nov., 12:22, Alex Young <a...@blackkettle.org> wrote:
> puts "this is a test".gsub( "a", "\\\\'" )
Thank you, you saved my day!
This really is confusing, because "\\'" gives me the correct result if
I don't use it with gsub:
puts "\\'" -> \'
Am I missing something here?
"\\'" translates to a literal backslash followed by '. This is what gsub gets.
gsub then sees \' and replaces it with $' the same way it would replace \1
with $1. To tell it not to do that it has to get \\', so it knows it's not
supposed to treat \' as special. In order to archieve that you have to
write "\\\\'". Hope that cleared things up for you.