# Replacing ' with \\'

**URL:** <https://www.ruby-forum.com/t/replacing-with/148396>\
**Category:** Ruby\
**Created:** [September 12, 2008, 2:26pm UTC](https://www.ruby-forum.com/t/replacing-with/148396 "2008-09-12T14:26:00Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![nixon](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/5fc32e/32.png) [@nixon](https://www.ruby-forum.com/u/nixon)\
**Post date:** [September 12, 2008, 2:26pm UTC](https://www.ruby-forum.com/t/replacing-with/148396/1 "2008-09-12T14:26:00Z")

</div>

In my practice I need to replace apostrophe with backslash and  
apostrophe in string. I using String#gsub, but it has unpredictable  
result in my own. That’s I do in IRB to test my gsub call:

irb(main):001:0\> str = “O’Reilly”  
=\> “O’Reilly”  
irb(main):002:0\> str.gsub("’", “\’”)  
=\> “OReillyReilly”

As You see I have magic result: I want to have “O\'Reilly”, but result  
is one - “OReillyReilly”.

Does anybody known how to fix this problem? Thanks.

---

<div class="post-metadata">

**Author:** ![nixon](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/5fc32e/32.png) [@nixon](https://www.ruby-forum.com/u/nixon)\
**Post date:** [September 12, 2008, 2:30pm UTC](https://www.ruby-forum.com/t/replacing-with/148396/2 "2008-09-12T14:30:24Z")

</div>

Nikita P. wrote:

> In my practice I need to replace apostrophe with backslash and  
> apostrophe in string. I using String#gsub, but it has unpredictable  
> result in my own. That’s I do in IRB to test my gsub call:
> 
> irb(main):001:0\> str = “O’Reilly”  
> =\> “O’Reilly”  
> irb(main):002:0\> str.gsub("’", “\’”)  
> =\> “OReillyReilly”
> 
> As You see I have magic result: I want to have “O\'Reilly”, but result  
> is one - “OReillyReilly”.
> 
> Does anybody known how to fix this problem? Thanks.

The backslash has a special meaning in gsub. Use str.gsub("’", “\\’”)  
instead.

TPR.

---

<div class="post-metadata">

**Author:** ![nixon](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/5fc32e/32.png) [@nixon](https://www.ruby-forum.com/u/nixon)\
**Post date:** [September 12, 2008, 3:08pm UTC](https://www.ruby-forum.com/t/replacing-with/148396/3 "2008-09-12T15:08:19Z")

</div>

Thomas B. wrote:

> The backslash has a special meaning in gsub. Use str.gsub("’", “\\’”)  
> instead.

Thanks, that helped me.
