From: Brian Candler Date: 2011-04-08T00:50:48+09:00 Subject: Re: String.gsub with regex and block Alexey Petrushin wrote in post #991484: > Probably a stupid question, but is there a way to use :gsub replacement > without $0 $1 $2 $3 (and without "\0\1\2\3")? There is also $~ (Regexp.last_match); $1/$2/etc are just a facade. > I would prefer something like: > > "John Smith".gsub /(.+)\s(.+)/ do |name, family| > p [name, family] > > # instead of this > p [$1, $2] > end "John Smith".gsub /(.+)\s(.+)/ do name, family = $~.captures p [name, family] end Not pretty, but you can wrap it up in your own method: class String def gsubcap(*arg) gsub(*arg) { yield $~.captures } end end "John Smith".gsubcap /(.+)\s(.+)/ do |name, family| p [name, family] end -- Posted via http://www.ruby-forum.com/.