From: RichardOnRails Date: 2011-01-18T05:40:21+09:00 Subject: Re: A tad of meta-programming needed On Jan 17, 7:38 am, botp wrote: > On Mon, Jan 17, 2011 at 2:05 PM, Josh Cheek wrote: > > On Sun, Jan 16, 2011 at 11:30 PM, RichardOnRails < > > The matchdata object implements the same inteface as a hash. If that is all > > you need, on 1.9 you could just name the capture groups, then use the > > MatchData object and not have to do any assignment/creation at all. > > (Assuming this data is based on the pastie you posted earlier, this code > > would work) > > RUBY_VERSION # => "1.9.2" > > line = "Apple 1.1234 1/2/3 4/5/6 $1,234.56 $7 ($5)" > > regex = /^(?       .+                       )\s > >          (?   \d+\.\d{4}               )\s+ > >          (? \d\d?\/  \d\d?\/  \d\d?  )\s+ > >          (? \d\d?\/  \d\d?\/  \d\d?  )\s+ > >          (?   [\$\d,\.]+               )\s+ > >          (?       [\$\d,\.]+               )\s+ > >          (?  [\(\)\$,\d \.]+          )\s* > >        $/x > > result = regex.match(line) > > or for older reg engines, they can do parallel assignments w array or splat > > something like > > _,:name,:n_shares,:opened = regex.match(line).to_a > > or > > _,:name,:n_shares,:opened = *regex.match(line) > > best regards -botp Hi botp, Thanks for that very interesting approach. It's beautifully succinct. I tried running it on my WinXP-Pro/SP3 machine running Ruby 1.8.6 and was unsuccessful in running your example. I probably overlooked some detail, for which I apologize. Here's what I ran: _, :name, :shares, :opened_MDY, :closed_MDY, :proceeds, :cost, :gainLoss = regex.match(line).to_a I got: ProcessTaxData.rb:116: syntax error, unexpected ',', expecting tCOLON2 or '[' or '.' _, :name, :shares, :opened_MDY, :closed_MDY, :proceeds, :cost, :gainLoss = regex.match(line).to_a ^ I ran this in SciTE 1.74, where the output is rendered in monotype font, I believe. So SciTE actually displayed the "^" under the "m" of the ":name" symbol, despite the rendering above. While the symbols didn't work, using local variables did in this simple test: string = "abc 123x45" regex = /(\w+)\s*(\d+)/ puts "Test 1" _, @x, @y = regex.match(string).to_a puts @x, @y # => abc and 123 on successive lines Do you have a working example with symbols you could provide me? And what version of Ruby ran it? Again, thanks for helping with my Ruby education. Best wishes, Richard