Remember that there is a third option, the block form sub . Sometimes you need it. Suppose you want to replace some text with reverse text. You cannot use $ 1 because it is not bound fast enough:
"foobar".sub(/(.*)/, $1.reverse)
You also cannot use \1 , because the sub method just does the text substitution \1 with the corresponding captured text, there is no magic here:
"foobar".sub(/(.*)/, '\1'.reverse)
So, if you want to do something interesting, you should use the sub block form ($ 1, $ 2, $ `, $ ', etc.):
"foobar".sub(/.*/){|m| m.reverse}
Brian Carper Nov 13 '08 at 23:01 2008-11-13 23:01
source share