Shagymoe
Shagymoe

Reputation: 1456

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.

Upvotes: 3

Views: 283

Answers (2)

jxpx777
jxpx777

Reputation: 3641

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" }

Upvotes: 9

mpapis
mpapis

Reputation: 53178

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

Upvotes: 0

Related Questions