Hi --

On Sat, 16 Nov 2002, Holden Glova wrote:
>
> On Sat, 16 Nov 2002 10:19, Michael Campbell wrote:
> >
> > > irb(main):016:0> def foo(s)
> > > irb(main):017:1> re = /#{s}/o
> > > irb(main):018:1> p re
> > > irb(main):019:1> re = nil
> > > irb(main):020:1> end
> > > nil
> > > irb(main):021:0> foo("a")
> > > /a/
> > > nil
> > > irb(main):022:0> foo("b")
> > > /a/
> > > nil
> > >
> > > and I'm confused even more.
> >
> > That's the SAME regex (same spot in the source code) used twice.
> > Your first example was 2 different regex's, used once each.
>
> I'm not sure I can agree that this is the same regex, Jim is setting
> it to nil at the end of the function so that also is 2 different
> regex objects. What sort of voodoo is going on here? I too am
> confused. I didn't know about the /o modifier and I think it is
> pretty cool, now if it just made sense to me.... :)

(Picking up on our irc discussion of this :-)

The assigning of the regex to a variable, followed by the assigning of
something else to the same variable, is sort of a no-op, since all it
does is increase the reference count by one and then reduce it by one.
The behavior of /o can be seen in this somewhat simpler example:

  irb(main):017:0> def make_re(s); /#{s}/o; end
  nil
  irb(main):018:0> make_re("a")
  /a/
  irb(main):019:0> make_re("b")
  /a/

In effect (though perhaps not really, internally), the /o modifier
seems to be sort of retro-creating a constant.  So the effect is as if
one had typed:

  REGEX = /a/
  def make_re(s)
    REGEX
  end

This happens the first time through -- in keeping with the "compile
once" principle of the /o -- and thereafter the expression #{s} is not
evaluated dynamically again (even though it looks like it should/will
be).

In the other case that was being discussed:

  irb(main):035:0> s = "a"
  "a"
  irb(main):036:0> /#{s}/o
  /a/
  irb(main):037:0> s = "b"
  "b"
  irb(main):038:0> /#{s}/o
  /b/

there's no connection or common context between the two regexes.
Here, it's as if one had typed:

  s = "a"
  REG1 = /a/
  REG1
  s = "b"
  REG2 = /b/
  REG2

So (I assume) something like the same process of one-time compilation
is adhered to -- but that's one time per lexical regex, and two
lexically distinct regexes are not affected by each other.


David

-- 
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav