Skip to content

Instantly share code, notes, and snippets.

@cpjolicoeur
Created April 29, 2009 01:35
Show Gist options
  • Save cpjolicoeur/103523 to your computer and use it in GitHub Desktop.
Save cpjolicoeur/103523 to your computer and use it in GitHub Desktop.
## 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??
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment