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

···

On 1/3/07, Trish Ball <trish.ball@gmail.com> wrote:

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

Hi --

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

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

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

···

On Thu, 4 Jan 2007, Trish Ball wrote:

On 1/3/07, Trish Ball <trish.ball@gmail.com> wrote:

--
Q. What is THE Ruby book for Rails developers?
A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black\)
    (See what readers are saying! http://www.rubypal.com/r4rrevs.pdf\)
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)