Forum: Ruby Problems with Sting#sub and regular expressions

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
De8c393deb01f7157eb4ce896a2cd4a6?d=identicon&s=25 Trish Ball (Guest)
on 2007-01-03 16:14
(Received via mailing list)
I have been working on an expression using String#sub and am getting
inaccurate results on the first time I run the expression, but not on
following times I run it.  Is there something wrong with my regular

The intent of my regular expression is to remove preceding spaces and

irb(main):001:0> " ' Helen".sub(/^(['\s]*)(.*)/, "#{$2}")
=> ""
irb(main):002:0> " ' Helen".sub(/^(['\s]*)(.*)/, "#{$2}")
=> "Helen
De8c393deb01f7157eb4ce896a2cd4a6?d=identicon&s=25 Trish Ball (Guest)
on 2007-01-03 16:20
(Received via mailing list)
I did change my expression to read:

irb(main):001:0> " ' Helen".sub(/^(['\s]*)/, "")
=> "Helen"

and that works on the first try... but I was just wondering why the
example does not work.

1fba4539b6cafe2e60a2916fa184fc2f?d=identicon&s=25 unknown (Guest)
on 2007-01-03 16:46
(Received via mailing list)
Hi --

On Thu, 4 Jan 2007, Trish Ball wrote:

>> irb(main):001:0> " ' Helen".sub(/^(['\s]*)(.*)/, "#{$2}")
>> => ""
>> irb(main):002:0> " ' Helen".sub(/^(['\s]*)(.*)/, "#{$2}")
>> => "Helen

What's happening is that you're sort of inter-leafing (-leaving?) the
setting and using of $2.  The $2 you use in the first replacement
string is nil; in that context, it won't pick up the match you just

Here's a simpler example, for illustration:

irb(main):002:0> "abc".sub(/(a)/, "#$1")
=> "bc"
# $1 was nil, so the 'a' got deleted.  But *now* $1 is 'a' (from the
# line that was just executed).  Therefore...

irb(main):003:0> "abc".sub(/(a)/, "#$1")
=> "abc"
# ...this time, 'a' gets replaced with 'a'.

This topic is locked and can not be replied to.