Simple Substitution with Capture
If you use parentheses in your regular expression to capture portions of the string, these are available to you as \1, \2, etc. Where \1 is the first capture group and \2 the second, etc.
"Superman and Batman".sub(/(\w+) and (\w+)/, '\2 and \1')You will need to escape the backslash if your replacement string is specified in double quotes.# => Batman and Superman
"Superman and Batman".sub(/(\w+) and (\w+)/, "\\2 and \\1")# => Batman and Superman