The task is simple – I have a string like "I don't know" and I want substitute ' with \' (I know that I don’t have to escape single quotes). How can I do it?
The task is simple – I have a string like I don’t know and
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Try using the block form, it should work in all versions of Ruby:
[Edit]
The reason is that the
gsubmethod has special handling for backslash sequences in the replacement string which correspond to the special match variables. So you can use$'(and$1, etc.) directly in the substituted string by using the form\\'(and\\1, etc.) instead.The block form of gsub doesn’t have this behavior, so that’s the workaround when you’re trying to sub in a string that looks like a special backslash sequence.