Forum: Ruby Double characters in string

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
4c032774402a9fe5ae814b6318c75a60?d=identicon&s=25 Dennie Mans (wouss)
on 2008-11-05 08:54
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
E088bb5c80fd3c4fd02c2020cdacbaf0?d=identicon&s=25 Jesús Gabriel y Galán (Guest)
on 2008-11-05 09:46
(Received via mailing list)
On Wed, Nov 5, 2008 at 8:53 AM, Wouss Bla <wvdongen@zonnet.nl> 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.
This topic is locked and can not be replied to.