From: Heesob Park Date: 2009-04-29T12:24:50+09:00 Subject: Re: Issue with regexp pattern matcher withing String#gsub 2009/4/29 Craig Jolicoeur : > I'm having a strange issue I can't wrap my head around.  I've posted the > full details as a gist here: http://gist.github.com/103523 but I will > also paste the same contents here for everyones benefit. > > ## The pattern matcher in both the following will match either the > single or double quote > ## at the start of the src= attribute (this is what is available in $1 > > ## this regexp replacement works fine and will convert > ## src="/foo/bar.png" > ## to > ## src="/RAILS_ROOT/public/foo/bar.png" > > html_string.gsub!( /src=(["'])[\.\/]/ ) { |m| 'src=' + $1 + > "#{RAILS_ROOT}/public/" } > > ## this regexp errors with the following error message > ## TypeError: can't convert nil into String > ##  from (irb):84:in `+' > ##  from (irb):84 > ##  from (irb):84:in `gsub' > ##  from (irb):84 > > html_string.gsub!( /src=(["'])\S+\?\d*\1/ ) { |s| s.split('?').first + > $1 } > > ## the question is why can I do string concat with + $1 in the first > regexp and > ## why am I unable to do it in the second regexp where doing str + $1 > throws the error?? The side effect of String#split is changing the value of $1. You can work acound like this: html_string.gsub!( /src=(["'])\S+\?\d*\1/ ) {|s| t=$1;s.split('?').first + t } Regards, Park Heesob