Search code examples
rubystringsubstitutionbackslash

Ruby replace backslash with double backslash in a String


I have this little problem that bugs me. I need to double every backslash in a string, for exaple, If have a string 1 \ 2, I whish to transform it into 1 \\ 2. I don't see why the code below fails. Can you help? PS. Please don't tell me to split in chars and operate on the list elements then join ;) I need to know if this is a bug in sub or if i am missing something. bye

irb> s = '1 \\ 2'
irb> puts s
1 \ 2
irb> s.size 
5
irb> s[2]
"\\"
# now i try to do the substitution
irb> s2 = s.sub('\\', '\\'*2)   # or '\\\\'
"1 \\ 2"
irb> s2.size
5

Solution

  • Note that \\ is interpreted as an escape, i.e., a single backslash.

    Note also that a string literal consumes backslashes. See string literal for details about string literals.

    A back-reference is typically preceded by an additional backslash. For example, if you want to write a back-reference \& in replacement with a double-quoted string literal, you need to write "..\\&..".

    If you want to write a non-back-reference string \& in replacement, you need first to escape the backslash to prevent this method from interpreting it as a back-reference, and then you need to escape the backslashes again to prevent a string literal from consuming them: "..\\\\&..".

    https://ruby-doc.org/3.2.2/String.html#class-String-label-Substitution+Methods

    What that means is you need more backslashes:

    >> "1 \\ 2".sub("\\", "\\"*4)
    => "1 \\\\ 2"
    # or
    >> "1 \\ 2".sub("\\", Regexp.escape("\\\\"))
    => "1 \\\\ 2"