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
-Charlie