开发者

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜