On Sun, Nov 21, 2010 at 11:57 AM, botp <botpena / gmail.com> wrote:
> On Sun, Nov 21, 2010 at 6:13 AM, Ralph Shnelvar <ralphs / dos32.com> wrote:
>> 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.
>
> there are many ways,
>
> #1
> "\\1\\2\\3".gsub(/(\\)/,"\\1\\1").scan /./
> #=> ["\\", "\\", "1", "\\", "\\", "2", "\\", "\\", "3"]
>
> #2
> "\\1\\2\\3".gsub(/(\\)/,'\1\1').scan /./
> #=> ["\\", "\\", "1", "\\", "\\", "2", "\\", "\\", "3"]
>
> #3
> "\\1\\2\\3".gsub(/\\/){"\\\\"}.scan /./
> #=> ["\\", "\\", "1", "\\", "\\", "2", "\\", "\\", "3"]
>
> #4
> "\\1\\2\\3".gsub(/(\\)/){$1+$1}.scan /./
> #=> ["\\", "\\", "1", "\\", "\\", "2", "\\", "\\", "3"]
>
>
> #1 & #2 samples uses group backreferences, ruby may need second parsing pass
> for this feature to work...
>
> #3 & #4 uses code blocks. may not need second pass. backreferences can be
> had using $n notation.

botp's excellent suggestions reminded of another one:

>> "\\1\\2\\3".gsub(/\\/, '\&\&')
=> "\\\\1\\\\2\\\\3"

Regards,
Ammar