From: RichardOnRails Date: 2011-01-23T11:45:30+09:00 Subject: Re: A tad of meta-programming needed On Jan 20, 8:19 am, Robert Klemme wrote: > On Mon, Jan 17, 2011 at 9:40 PM, RichardOnRails > > wrote: > > Do you have a working example with symbols you could provide me?  And > > what version of Ruby ran it? > > Basically you need a mapping from symbols to group indexes to make > named groups work in 1.8.  There are several ways you can do that > > 1. manual > > names = [:foo, :bar, :baz] > .. > md = rx.match str > puts md[names.index(:foo) + 1] > > 2. semi automatic > > names = [:foo, :bar, :baz] > > def names.get(md, name) >   md[names.index(:foo) + 1] > end > .. > md = rx.match str > puts names.get(md, :foo) > > 3. or even > > class MatchData >   attr_accessor :names > >   def get(name) >     self[names.index(name) + 1] >   end > end > .. > md = rx.match str > md.names = names > puts md.get(:foo) > > Further variants are possible.  But I'd switch to 1.9 soon - because > it's faster and has a better regexp engine with named captures. > > Kind regards > > robert > > -- > remember.guy do |as, often| as.you_can - without endhttp://blog.rubybestpractices.com/ Hi Robert, Thanks for your response. As usual, it seems to me, your response was thorough. > Further variants are possible. But I'd switch to 1.9 soon - because > it's faster and has a better regexp engine with named captures. Another responder pointed out the advantage of upgrading to 1.9, which I will do in a couple of weeks. My original wish was to use the values from a regex match ($1, $2 ...) without explicitly listing those symbols in an expression. Rather I wanted to extract the values from them in a loop. Having done some Ruby meta-programming in past, but suffering from an increasingly poor memory in my dotage, I jotted down "eval($ + i.to_s)", which failed. Su Zhang on this thread corrected my error: "put the & in quotes", along with alternatives. Problem solved. Happily, I received a number of other approaches, which I saved because I love to employ programmatic ways to avoid repetitive program code. And now I have the good fortune of getting a bunch of clever alternatives from you, which I will store with my other gifts. Since my original problem has been solved, I'm going to keep on pushing my project forward. But I treasure these gifts and promise to employ them in my continuation education in art of Ruby programming. Best wishes, Richard