String#gsub is one of the most used Ruby methods in the wild. Just
about every Ruby programmer knows about the method and uses it fairly
Here’s a quick refresher of the typical
1 2 3 4 5 6 7
Basically we can replace string and regexp matches with other
strings. When doing regexp matches we can access the matched groups
\2, etc and embed them in the replacement
string. Sometimes, however, some additional processing of the matched
data might be required. Consider this trivial example – we might want
to increment a matched number by 1. Here
gsub’s version that takes a
block comes into action:
1 2 3
Basically we’re replacing the matched portion of the string with the result of the block. While the param enhances the readability of the code it’s not necessary:
1 2 3
Regexp.last_match is the OO version of the obscure (but pretty
$1. In this particular case using the block param
(as in the first example) is obviously a better idea.
Note that some people expect that
gsub would yield to the block all
the matched groups as arguments – that is not the case, you’ll always
get a single argument denoting the entire regexp match.
Keep this in mind!
That’s all for today folks! I hope you’ll find this short article useful!