Ruby string operation not working with captured group
This string substitution works:
"reverse, each word".gsub(/(\w+)/, "\\1a")
=> "reversea, eacha worda"
and so that basically the same thing: single quotes:
"reverse, each word".gsub(/(\w+)/, '\1a')
=> "reversea, eacha worda"
but if I try to change the line, this will not work:
"reverse, each word".gsub(/(\w+)/, "\\1a".reverse)
=> "a1\\, a1\\ a1\\"
I played with him, but I can not get the reverse operation to work.
I run into this all the time. Capture groups are available in the block area, so rewrite it like this:
"reverse, each word".gsub(/(\w+)/) { |match| $1.reverse + "a" }
or since your match is a group, you can completely omit the group
"reverse, each word".gsub(/\w+/) { |match| match.reverse + "a" }