On Apr 2, 3:35 pm, "Thomas Wieczorek" <wieczo... / googlemail.com>
wrote:
> On Wed, Apr 2, 2008 at 10:12 PM, Wybo Dekker <w... / servalys.nl> wrote:
> > Why do I get "xx" instead of "x" in the following:
>
> >  $ irb
> >  >> 'test'.gsub(/.*/,'x')
> >  => "xx"
>
> .* matches NO and ALL characters, so gsub() substitutes
> ''(empty)(=>'x') and and 'test'(=>'x') with x, so you get 'xx'

That sounds like an explanation why ''.gsub(/.*/, 'x') is 'x' more
than why 'test'.gsub(/.*/, 'x') is 'xx'. It seems to me that the .*
should match [empty string]test[empty string] just once.

> >  and even more confusing (to me):
>
> >  >> "x\n".gsub(/.*/,'y')
> >  => "yy\ny"

This makes sense because . doesn't normally match \n, so there's the
replacement before and after. Still, the double replacement when there
are actual characters is just weird.

> Same goes here as above. If you want to replace each character use
> 'test'.gsub(/./,'x') #=> 'xxxx'
> or if you want to replace all characters in each line, use
> "test\ntest".gsub(/.+/,'x') #=> "x\nx"

--
-yossef