The fact your second example does not work, has nothing to do with the order in which the if
is being evaluated.
Instead, use \1
and \2
as interpolation variables.
str = "This is a string"
str.gsub!(/(\w+)/, '1\1')
print str
Also note that "\1"
is interpolated, you need '\1'
.