简体   繁体   中英

Ruby string operation doesn't work on captured group

This 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM