Search code examples
rubystringbackslashquoting

\' (backslash, single quote) in a Ruby string


I am using Ruby 1.8.7, trying to generate a string with the \' characteres, in order to create a script for running in MySQL. The result should be like this:

INSERT INTO table (name, description) values ('Joana d\'Arc', '')

But i can't get just one backslash in a ruby string. Using the following code:

string = "INSERT INTO table (name, description) values ('Joana d\\'Arc', '')"

I got the following string:

INSERT INTO table (name, description) values ('Joana d\\'Arc', '')

And with:

string = "INSERT INTO table (name, description) values ('Joana d\'Arc', '')"

I got this string:

INSERT INTO table (name, description) values ('Joana d'Arc', '')

Solution

  • The reason puts works is that it shows what is actually in the string. The bare console is showing the string escaped. Try this on the console:

    "Joana d\\'Arc".size
    

    You will get back 12. If both backslashes were there you should get 13.

    Hauleth's answer should work.