Replacing `\` with `\\` in ruby

95 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 best solutions below

1
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
On

A bit shorter

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

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

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