From: Brian Candler Date: 2003-05-25T01:42:22+09:00 Subject: Re: why is "does" missing from this sub!-stitution? On Sat, May 24, 2003 at 10:23:22AM +0900, dblack@superlink.net wrote: > So the order of things seems a little odd: > > /(..)/.match("abcdef") # match operation, $1 set > "abcdef".sub(/(..)/, "#$1") # match operation, $1 *not* set > then string parsed, > *then* $1 is set In the second case, /(..)/ simply creates a Regexp object, like Regexp.new("(..)"). It does not match it against anything. This regexp is passed as a parameter to sub; it is inside sub that the regexp is actually used. You could write it like this: class String def mysub(regexp, newstr) if regexp =~ self return $` + newstr + $' end self end end "abcdefabcdef".mysub(/de/,'zz') #>> "abzzefabcdef" (except to get the full functionality, after doing the match you'd replace '\' '1' in newstr with the contents of $1, '\' '2' with $2, etc) Regards, Brian.