Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby string operation doesn't work on captured group

Tags:

string

regex

ruby

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.

like image 489
Shagymoe Avatar asked Jan 25 '26 06:01

Shagymoe


1 Answers

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" }
like image 137
jxpx777 Avatar answered Jan 26 '26 21:01

jxpx777