Hector wrote:
> Help!
>
> How do I get $1, $2, and $3 to get interpolated in the following
> snippet?
>
> string = 'This is a test of the emergency'
> regexp = Regexp.new('(\W)+(\w\w)(\W)+')
> replacement = '$1->$2<-$3'
> user_wants_upcase=FALSE
>
> # Note: All variables above are set by the user of the program, so I
> don't know
> # what they will contain before runtime.
>
> string.gsub!(regexp) {
>   return_value = string # Here, how do I get $1, $2, and $3 to
> interpolate?
>
>   if (user_wants_uppercase)
>     return_value.upcase! || return_value
>   end
>
>   return_value
> }
>
> I want return_value to be -> 'This ->is<- a test ->of<- the emergency'
>
> Note: I know that I can get it to work with the non-block version of
> gsub! but I need to use the block version.

In your case you don't even need groups, because you can nicely anchor the
expression on word boundaries:

>> upcase=true
=> true
>> 'This is a test of the emergency'.gsub(/\b\w\w\b/) {|m| "->" << (upcase
? m.upcase : m) << "<-"}
=> "This ->IS<- a test ->OF<- the emergency"

Otherwise

>> 'This is a test of the emergency'.gsub(/(\W)+(\w\w)(\W)+/) {|m|
"#$1->#{upcase ? $2.upcase : $2}<-#$3"}
=> "This ->IS<- a test ->OF<- the emergency"

Note: #$1 in a double quoted string is a shortcut for #{$1}.

Kind regards

    robert