Double escaping backslashes in ruby.
If you have a string that looks like:
\
and you want it to look like:
\\
in ruby, you have to do the following:
Code (ruby)
-
-
irb(main):070:0> str = "\\"
-
=> "\\"
-
irb(main):071:0> puts str
-
\
-
=> nil
-
irb(main):073:0> puts str.gsub("\\", "\\\\\\\\")
-
\\
-
=> nil
-
In Ruby, you can use perl-style regular expression numbered group references in replacement strings (ie \\1 = the first captured group of the regexp). So, to make a literal backslash in gsub, you need “\\\\”. And to make the second one, you need “\\\\\\\\”.
0 Comments