Greetings,
I’m trying to do something that should be very simple: stick a “” in
front of
every instance of “&” in a string. However, the obvious code…
“this&that”.gsub!("&", “")
–> "thisthat” # OK!
“this&that”.gsub!("&", “\&”)
–> “this&that” # Wrong
…doesn’t work, because “&” means “last match” in gsub substitution
strings.
How can I escape this? I experimentally determined that entering
“\\\&”
(that’s six backslashes) gets the desired result, but I don’t really
understand why. Is there a less obscure way of doing this?
Cheers,
-jani
On Mon, Oct 09, 2006 at 08:58:09PM +0900, Jani Patokallio wrote:
–> “this&that” # Wrong
…doesn’t work, because “&” means “last match” in gsub substitution
strings.
How can I escape this? I experimentally determined that entering
“\\\&”
(that’s six backslashes) gets the desired result, but I don’t really
understand why. Is there a less obscure way of doing this?
I'm not sure, but I think that the problem is that you are using
double
quotes. So, the value you are passing is really the same as:
'\\\&'
Which, once you interpret the escape sequences, you have a literal ‘’
and a
literal ‘&’…
this was discussed several times, try searching for gsub and \ or
escaping or something similar. & is the last match, and \ is the
whole match. so you need to escape both. The correct solutions to this
‘quiz’ are posted somewhere, just google it 