"reversea...">

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.

+3
source share
2 answers

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" }
+9
source

You ordered the ruby ​​to replace all occurrences of / (\ w +) / with "\ 1a" .reverse

"reverse, each word".gsub(/(\w+)/, "\\1a".reverse)

You would probably want to change the result without replacing the line:

"reverse, each word".gsub(/(\w+)/, "\\1a").reverse
0
source

Source: https://habr.com/ru/post/1774329/


All Articles