I’m trying to replace backslashes in my string with two backslashes like so:
str.gsub!("\\", "\\\\")
But, it doesn’t do anything. I’m confused…
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.
This works:
Edit: Explanation (via http://www.ruby-forum.com/topic/143645 provided by @vache)
Disclaimer: I’m not familiar with the inner workings of ruby’s regex engine, any info here is deducted from the article mentioned above.
The basic thing to know is that the replacement string gets evaluated 2 times.
The first time the slashes do their job as escapes in the string, in the second time gsub will search the string for group references.
as @chris-johnsen mentioned, 6 slashes do not alway work. This leads me to believe something like this is happening:
For 6 slashes. 3 slashes are passed to the group reference layer. The trailing slash is interpreted not as an escape character because nothing is coming after it, it is interpreted as a backslash. So finally this layer returns 2 slashes. If anything would be trailing it, the expression will fail, as the third slash will now function as an escape character.
For 8 slashes: 4 slashes are passed to the group reference layer. The four slashes will in turn be reduced to two.