Ruby string operation doesn't work on captured group
T开发者_运维问答his string substitution works:
"reverse, each word".gsub(/(\w+)/, "\\1a")
=> "reversea, eacha worda"
and like this, which is basically the same thing with single quotes:
"reverse, each word".gsub(/(\w+)/, '\1a')
=> "reversea, eacha worda"
but if I try to reverse the string, it fails:
"reverse, each word".gsub(/(\w+)/, "\\1a".reverse)
=> "a1\\, a1\\ a1\\"
I've played with it, but can't seem to get the reverse operation to work.
I bump into this all the time. The capture groups are available in the block scope, so rewrite like this:
"reverse, each word".gsub(/(\w+)/) { |match| $1.reverse + "a" }
or since your match is the group, you could omit the group entirely
"reverse, each word".gsub(/\w+/) { |match| match.reverse + "a" }
You did ordered ruby to replace all occurrences of /(\w+)/ with "\1a".reverse
"reverse, each word".gsub(/(\w+)/, "\\1a".reverse)
You probably wanted to reverse result not the replacement string:
"reverse, each word".gsub(/(\w+)/, "\\1a").reverse
精彩评论