From: Robert Klemme Date: 2011-01-19T19:10:37+09:00 Subject: Re: Problem populating a hash with regex results 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($ + i.to_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) See http://www.geocities.jp/kosako3/oniguruma/doc/RE.txt Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/