Replacing `\` with `\\` in ruby

85 views Asked by At

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?

3

There are 3 answers

1
Yu Hao On BEST ANSWER
'\\'.gsub('\\', '\\\\')

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:

str.gsub(/\\/, '\\\\\\\\\')  # 8 backslashes!
0
Andrew Kozin On

A bit shorter

'\\'.gsub(/(\\)/, '\1\1')
0
knut On

You may also use Regexp.escape to escape your \:

puts '\\'.gsub('\\', Regexp.escape('\\\\'))