> Opening a fresh irb session (using Ruby 1.8.1 on OSX) I have the following
> problem with gsub:
> irb(main):001:0> name = "new_name"
> => "new_name"
> irb(main):002:0> ' self->hey '.gsub(/(\W)self(\W)/, "#{$1}#{name}#{$2}")
> => "new_name>hey "
> irb(main):003:0> ' self->hey '.gsub(/(\W)self(\W)/, "#{$1}#{name}#{$2}")
> => " new_name->hey "
> 
> Putting the following into a text file and feeding it to Ruby I get the
> same result.
> #!/usr/local/bin/ruby
> name = 'new_name'
> str = ' self->hey '
> puts str.gsub(/(\W)self(\W)/, "#{$1}#{name}#{$2}")
> puts str.gsub(/(\W)self(\W)/, "#{$1}#{name}#{$2}")
> 
> ####### output is:
> new_name>hey
>  new_name->hey 
> ####### end of output
> 
> Seems like $1 and $2 are nil the first time.A

Hi Charlie --

In the examples above, $1 and $2 are evaluated before the call to gsub even
gets going, and not on each match. Use \1 etc in the string, or pass in a
block.

See eg http://www.ruby-talk.org/blade/88377 and following thread.

-- George