chazmeyers.com/blog


Double escaping backslashes in ruby.

Posted in ruby by chazmeyers on the July 11th, 2007

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)
  1.  
  2. irb(main):070:0> str = "\\"
  3. => "\\"
  4. irb(main):071:0> puts str
  5. \
  6. => nil
  7. irb(main):073:0> puts str.gsub("\\", "\\\\\\\\")
  8. \\
  9. => nil
  10.  

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 “\\\\\\\\”.

Leave a Reply