On Dec 14, 2006, at 7:05 PM, Paul Lutus wrote:
> Benjohn Barnes wrote:
> /...
>
>> I would like gsub's block or second parameter to
>> provide an array, and for this to replace the captured parts of the
>> regexp, so:
>>
>> "axb".gsub(/(.)x(.)/, ['A', 'B'])
>>
>> would return:
>>
>> "AxB"
>>
>> gsub doesn't behave like this, but I imagine it would be possible to
>> build a gsub like function that did. :)
>
> result = "axb".gsub(/(.)(x)(.)/, "A\\2B" ) # gets what you want.
>
>> It would probably need to
>> inspect the regular expression given to it with a regular expression.
>
> Not really. Each of sub(), gsub() and scan() have their niche. It  
> is more a
> matter of learning how to use them.
>
> And, now that I think about it, your example using a provided array of
> replacement values can be implemented like this:
>
> rep = ['A', 'B']
>
> result = "axb".gsub(/(.)(x)(.)/, "#{rep[0]}\\2#{rep[1]}")
>
> And, I am sure, in many other ways.
>
> -- 
> Paul Lutus
> http://www.arachnoid.com

If you're not interested in the other groupings you can use (?:) to  
group the regexp without capturing.

rep = ['A', 'B']
result = "axb".gsub(/(?:.)(x)(?:.)/, "#{rep[0]}\\1#{rep[1]}")

Of course, these RE's don't even need to be grouped at all:

rep = ['A', 'B']
result = "axb".gsub(/.(x)./, "#{rep[0]}\\1#{rep[1]}")

And (x) is just a match for 'x', so you don't have to use a group at  
all.

In general, you could take your regexp, rewrite to capture the parts  
between the desired replacements, and use a replacement (or a block)  
similar to what Paul introduced to get the result you desire.

-Rob

Rob Biedenharn		http://agileconsultingllc.com
Rob / AgileConsultingLLC.com