# Gsub and slash-ampersand in the substitution string

**URL:** <https://www.ruby-forum.com/t/gsub-and-slash-ampersand-in-the-substitution-string/71498>\
**Category:** Ruby\
**Created:** [October 9, 2006, 1:58pm UTC](https://www.ruby-forum.com/t/gsub-and-slash-ampersand-in-the-substitution-string/71498 "2006-10-09T13:58:06Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jpatokal](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/b3f665/32.png) [@jpatokal](https://www.ruby-forum.com/u/jpatokal)\
**Post date:** [October 9, 2006, 1:58pm UTC](https://www.ruby-forum.com/t/gsub-and-slash-ampersand-in-the-substitution-string/71498/1 "2006-10-09T13:58:06Z")

</div>

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!("&", “_")  
–\> "this_that” # 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

---

<div class="post-metadata">

**Author:** ![jpatokal](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/b3f665/32.png) [@jpatokal](https://www.ruby-forum.com/u/jpatokal)\
**Post date:** [October 9, 2006, 2:07pm UTC](https://www.ruby-forum.com/t/gsub-and-slash-ampersand-in-the-substitution-string/71498/2 "2006-10-09T14:07:25Z")

</div>

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 ‘&’…

---

<div class="post-metadata">

**Author:** ![jpatokal](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/b3f665/32.png) [@jpatokal](https://www.ruby-forum.com/u/jpatokal)\
**Post date:** [October 9, 2006, 4:45pm UTC](https://www.ruby-forum.com/t/gsub-and-slash-ampersand-in-the-substitution-string/71498/3 "2006-10-09T16:45:48Z")

</div>

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 😉
