Question

I am using gsub method, and using //1 to get a back reference.

In that, say,

map = { "Stack" => "overflow"}

"Stackoverflow".gsub(/(Stack)overflow/,"Non\\1")

will print "NonStack". I am getting this correctly.

But I want to use map here, like

"Stackoverflow".gsub("/(Stack)overflow/","#{$map['\\1']}")  

so that it will print overflowoverflow. But i tried various combinations and I am not getting this.

Was it helpful?

Solution

You can use a block, then the global variables $1 .. $9 hold matches. This achieves what you want:

map = { 'stack' => 'overflow' }
p "stackoverflow".gsub(/(stack)(overflow)/) { map[$1] + $2 }
# => overflowoverflow

Alternatively, you can just pass a variable to the block:

map = { 'stack' => 'overflow' }
p "stackoverflow".gsub(/stack/) { |match| map[match] }
# => overflowoverflow

See String#gsub for reference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top