I'm trying to replace all occurrences of \
with \\
. Here was my first try:
> puts '\\'.gsub('\\', '\\\\')
\
I was pretty surprised when I saw the output. After some experimenting I was finally able to do what I wanted this this code:
> puts '\\'.gsub('\\', '\\\\\\')
\\
Why isn't the first piece of code working? Why do I need six backslashes?
When the substitution occurs, the substitution string
'\\\\'
is passed by the Regexp engine, and\\
is replaced by\
. The substitution string ends up as'\\'
, a single backslash.The idomatic way to replace any single bachslach to double is to use: