Problems with Sting#sub and regular expressions

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
the
following times I run it. Is there something wrong with my regular
expression?

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

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

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
previous
example does not work.

Thanks,
Trish

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
did.

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’.

David