On Sun, Nov 21, 2010 at 12:34 AM, Ammar Ali <ammarabuali / gmail.com> wrote:
> On Sun, Nov 21, 2010 at 12:13 AM, Ralph Shnelvar <ralphs / dos32.com> wrote:
>> Consider the string
>> \1\2\3
>> that is
>> "\\1\\2\\3"
>>
>> I feel really stupid ... but this simple substitution pattern does not do what I expect.
>>
>> "\\1\\2\\3".gsub(/\\/,"\\\\")
>>
>> What I want is to change single backslashes to double backslashes. The result of the above substitution is "no change"
>>
>> On the other hand
>> "\\1\\2\\3".gsub(/\\/,"\\\\\\\\")
>> does do what I want ... but I am clueless as to why.
>
> Backslashes are tricky. What's happening here is each escaped
> backslash "\\" yields one backslash, which affects (escapes) what
> comes after it, in this case another escaped backslash that in turn
> yields one back slash. In other words, four backslashes yield two
> backslashes, which is an escaped backslash (i.e one backslash).
>

I should have added that you can get the same result with 3
backslashes. So 6 of them will give you two.

>> "\\1\\2\\3".gsub(/\\/,"\\\\\\").scan /./
=> ["\\", "\\", "1", "\\", "\\", "2", "\\", "\\", "3"]

Regards,
Ammar