Eli Sadoff Eli Sadoff - 2 years ago 87
Ruby Question

Ruby gsub! with Regex keep word

I want to turn a string line

with regex. I currently have

string = "variable.to_s"

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download