From: Josh Cheek Date: 2011-01-17T15:05:11+09:00 Subject: Re: A tad of meta-programming needed --00163628369cf60fc7049a0490c4 Content-Type: text/plain; charset=ISO-8859-1 On Sun, Jan 16, 2011 at 11:30 PM, RichardOnRails < RichardDummyMailbox58407@uscomputergurus.com> wrote: > I've got the following hash set up and it works fine. But this took > more typing than programming. > > h = {:name=>$1, :n_shares=>$2, :opened_MDY=>$3, :closed_MDY=>$4, > :proceeds=>$5, :cost=> $6, :gain_Loss=>$7 > } > > So I'd like to get the following to work: > > field_names =%w GainLoss> > h = {} > (1..field_names.size).each { |i| h[field_names[i]] = eval($ + > i.to_s) } > > But concatenating the character "$" with the value of i converted to a > string, followed be evaluating that as a local variable isn't working > as I coded it. Can it be easily corrected? > > Thanks in Advance, > Richard > > 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) result # => # result[ :name ] # => "Apple" result[ :n_shares ] # => "1.1234" result[ :opened_MDY ] # => "1/2/3" result[ :closed_MDY ] # => "4/5/6" result[ :proceeds ] # => "$1,234.56" result[ :cost ] # => "$7" result[ :gain_Loss ] # => "($5)" --00163628369cf60fc7049a0490c4--