From: dblack@...
Date: 2003-05-24T07:31:51+09:00
Subject: Re: why is "does" missing from this sub!-stitution?
Hi --
On Fri, 23 May 2003, Brian Candler wrote:
> On Fri, May 23, 2003 at 08:44:16AM +0900, Dave Oshel wrote:
> > Maybe so, but this works as expected:
> >
> > `/sw/bin/fortune -m Nillity`.each { |x|
> > x.sub!( /(_+\010+)([a-zA-Z]+\b)/, "" + '\2' + "" )
> > print x
> > }
> >
> > Maybe it's a bug ... or a feature ... or a bug ... or a bug AND a
> > feature ... ;-)
>
> It's definitely a feature and not a bug. $2 behaves like a regular variable,
> and as you've seen, you have to use normal string interpolation #{...} to
> insert it. If $2=="foo" and you write the string "#{$2}" then it is
> interpolated as "foo", and *then* the resulting string is what you
> are passing as a parameter to 'sub'. If $2 is nil, then you pass "".
> So sub has no idea where to substitute any value.
It's interesting, though, that $2 hasn't been (re)evaluated by the
time the second argument to #sub is evaluated. Compare with:
irb(main):001:0> "abcdef".sub(s="d",s.upcase)
=> "abcDef"
My first thought by way of explaining the $2 behavior was: there's
been no assignment to $2, because the regex has been compiled but the
match hasn't happened yet. But then \2 wouldn't be meaningful.... So
I do actually start to wonder why the previous $2 (nil or otherwise)
persists so long.
David
--
David Alan Black
home: dblack@superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav