From: Tanaka Akira Date: 2007-12-23T11:00:11+09:00 Subject: Re: named captures assigning to local variables In article <63F5E6D9-ED10-4C13-B57D-F93552512DDE@mac.com>, Gary Wright writes: >> if /(?.)/ =~ str >> p foo >> end >> > > It isn't too hard to stuff matches into local vars > as it is: > > _, first, second = */(.+)\W+(.+)/.match("alpha beta") Unfortunately it is not usable in condition. if _, a, b = */(.)(.)/.match("ab") p [a,b] end causes a syntax error. So it needs two more lines. m = /(.)(.)/.match("ab") if m _, a, b = *m p [a,b] end > If I've got regular expressions that are sufficiently > complicated that I want to name the captures, I'm not sure I > will want them buried in code as a literal expression. I'd > probably define a constant for the RE just as I would for > any 'magic' numeric constant--at which point the local > variable assignment, as proposed, would be superfluous. The assignment is disabled if you use a regexp via a constant. > It would be even more awkward if the named captures in a > non-literal RE magically instantiated local variables. Yes. The assignment will never extended for non-literal regexps. If it is extended, it violates lexical scope. The performance issue, pointed by Charles, is another reason. > One final thought--I'm not sure I'd bother with the local > variables anyway if I can treat the match data object > like a hash: > > match = TWO_WORDS.match(text) > Customer.find_by_lastname(match[:second])) When this style is appropriate, it is usable. However, I don't think it is always better. -- Tanaka Akira