From: RichardOnRails Date: 2011-01-20T21:41:02+09:00 Subject: Re: Problem populating a hash with regex results On Jan 19, 5:10 am, Robert Klemme wrote: > On Mon, Jan 17, 2011 at 5:40 AM, RichardOnRails > > wrote: > > This is my current idea for succinct code to support further data > > analysis: > > >        field_names =%w > GainLoss> > >        h = {} > >        (1..field_names.size).each { |name| h[name] = eval($ + ito_s) } > > > Of course, that doesn't work,  but despite my perusing of Pragmatic's > > Programming Ruby, 2nd ed.,  I haven't so far figured out how to code > > that third line.  Any ideas.  If you're too busy, or whatever,  don't > > bother responding and I'll post about it tomorrow. > > If you are on 1.9 there is a better approach: named capture groups. > These let you use your MatchData object like a Hash: > > Ruby version 1.9.2 > irb(main):001:0> rx = /(?'name'\w+)\s*=\s*(?'value'\S+)/ > => /(?'name'\w+)\s*=\s*(?'value'\S+)/ > irb(main):002:0> md = rx.match " foo = 123 " > => # > irb(main):003:0> md[:name] > => "foo" > irb(main):004:0> md[:value] > => "123" > irb(main):005:0> md.names > => ["name", "value"] > irb(main):006:0> > > Note, there is an alternative syntax: (?rx) > > Seehttp://www.geocities.jp/kosako3/oniguruma/doc/RE.txt > > Kind regards > > robert > > -- > remember.guy do |as, often| as.you_can - without endhttp://blog.rubybestpractices.com/ Hi Robert, Thanks for your response. I didn't notice your reply because gave up on this thread and restarted on http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/6ddcea45d88ad810. I'm still running 1.8.6 'cause it's worked well for me. Like the song advises, "ya gotta dance with the guy that brung you." But I've copy your advice to apply it after this project's done, at which time I'll upgrade to 1.9.x. Again, thanks, Richars