[Note: parts of this message were removed to make it a legal post.]
I have a script with two lines:
puts "toads suck".gsub(/(\s)/, "\\#{$1}")
puts " a ".gsub(/(\s), "\\#{$1}")
I get broken output for the first:
toads\suck
\ a\
Can anyone explain why this is happening. I'm convinced it shouldn't ever
happen.
I'm sorry, but you're wrong.
When you pass "\\#{$1}" to gsub the
string is evaluated *once* and even worse, the value of $1 at time of
call has nothing to do with this gsub operation. gsub did not even
start matching at this point in time.
The second replacement apparently works because it gets $1 from the
first execution...
You also do not need the grouping because the group covers the whole
match anyway. You rather want a special replacement expression:
irb(main):001:0> "toads suck".gsub(/\s/, '\\\\\\&')
=> "toads\\ suck"
irb(main):002:0> puts "toads suck".gsub(/\s/, '\\\\\\&')
toads\ suck
=> nil
Note, the high number of backslashes is necessary because there are two
levels of escaping: first the string, i.e. you need two backslashes to
have one backslash in the string. Then you need to escape the backslash
you want to insert into the replacement because backslash is a
metacharacter in the substitution string itself.
Kind regards
robert