From: Robert Klemme Date: 2011-01-20T22:10:49+09:00 Subject: Re: Problem populating a hash with regex results On Thu, Jan 20, 2011 at 1:41 PM, RichardOnRails wrote: > 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. Well, let's see what we can do... irb(main):001:0> MDWrap = Struct.new :md, :fields do irb(main):002:1* def [](name) md[fields[name]] end irb(main):003:1> end => MDWrap irb(main):004:0> md = MDWrap.new("foobar".match(/(fo+)(ba\w+)/), :name=>1,:value=>2) => #, fields={:value=>2, :name=>1}> irb(main):005:0> md[:name] => "foo" or irb(main):007:0> names = {:name => 1, :value => 2} => {:value=>2, :name=>1} irb(main):008:0> md = "foobar".match(/(fo+)(ba\w+)/) => # irb(main):009:0> md[names[:name]] => "foo" Or you use indexes directly. :-) Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/