Eli Sadoff Eli Sadoff - 6 months ago 10
Ruby Question

Ruby gsub! with Regex keep word

I want to turn a string line

"variable.to_s"
into
"str(variable)"
using
gsub!
with regex. I currently have

string = "variable.to_s"
string.gsub!(/\w+\.to_s/,/str(\w)/)


which obviously does not work as you cannot use regex in the second part of gsub, but how do I keep the
\w
found in the gsub part but replacing the
.to_s
part?

Answer

You're capturing the wrong thing:

string.gsub!(/(\w+)\.to_s/, 'str(\1)')

gsub and gsub! take a string or regular expression as the first argument and a string or block as the second argument. You're sending a regular expression to both.

If you need to use a portion of the match in the second part, capture it with brackets. You did this inadvertently in your code but on the wrong side.