# Double characters in string

**URL:** <https://www.ruby-forum.com/t/double-characters-in-string/152569>\
**Category:** Ruby\
**Created:** [November 5, 2008, 8:54am UTC](https://www.ruby-forum.com/t/double-characters-in-string/152569 "2008-11-05T08:54:42Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![wouss](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/aca169/32.png) [@wouss](https://www.ruby-forum.com/u/wouss)\
**Post date:** [November 5, 2008, 8:54am UTC](https://www.ruby-forum.com/t/double-characters-in-string/152569/1 "2008-11-05T08:54:42Z")

</div>

Hi,

I’m looking for a way to put a ‘X’ between all double characters in a  
string. So if this would be the string: ‘hello, I just said hello’ would  
be changed into ‘helXlo, I just said helXlo’.

I tried:

text = text.sub(/([a-z])\1/,’\1x\1’)

But this only changed the first double character…

Thanks in advance

---

<div class="post-metadata">

**Author:** ![wouss](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/w/aca169/32.png) [@wouss](https://www.ruby-forum.com/u/wouss)\
**Post date:** [November 5, 2008, 9:46am UTC](https://www.ruby-forum.com/t/double-characters-in-string/152569/2 "2008-11-05T09:46:52Z")

</div>

On Wed, Nov 5, 2008 at 8:53 AM, Wouss B. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> But this only changed the first double character…  
> From ri:

## ------------------------------------------------------------- String#sub str.sub(pattern, replacement) =\> new\_str str.sub(pattern) {|match| block } =\> new\_str

```
 Returns a copy of _str_ with the _first_ occurrence of _pattern_
 replaced with either _replacement_ or the value of the block.

```

So it only replaces the first occurrence. Try gsub:

## ------------------------------------------------------------ String#gsub str.gsub(pattern, replacement) =\> new\_str str.gsub(pattern) {|match| block } =\> new\_str

```
 Returns a copy of _str_ with _all_ occurrences of _pattern_
 replaced with either _replacement_ or the value of the block

```

irb(main):001:0\> “hello, I said hello”.gsub(/([a-z])\1/,‘\1x\1’)  
=\> “helxlo, I said helxlo”

Jesus.
