From: Josh Cheek Date: 2011-01-17T09:06:38+09:00 Subject: Re: Problem populating a hash with regex results --0016e64f47cec3def40499ff86c4 Content-Type: text/plain; charset=ISO-8859-1 On Sun, Jan 16, 2011 at 5:45 PM, RichardOnRails < RichardDummyMailbox58407@uscomputergurus.com> wrote: > Hi, > > I've got a text file with 7 fields. I successfully extract the data > on each with a regex and for debugging purposes print each lines > fields. > > Now I want to edit and organize the data for subsequent processing. > But populating the hash fails. I posted the code on > http://www.pastie.org/1468271 > > The "puts" on line 15 shows that the regex captures the 7 fields in > the text file. > Lines 17-19 is an attempt to build a hash using the known values in > the $n variables. > That attempt fails because line 21 shows that it's nil instead the > string 100.0000 reported by line 15. > > Maybe I should just build an array of the extracted values and use the > symbols I've created to index the array. In the mean time, mainly > for my education, I'd like to know where I went wrong with this hash. > > Thanks in Advance, > Richard > > Hi, Richard. It looks like your problem is that you put your data into your hash with `:n_shares=>$2`, on line 17, but you pull it out with `puts h[:shares]`, on line 21. When you get in weird situations like that, where it seems correct on one line, and incorrect just a few later, give yourself a sanity check by breaking it down into as small of steps as possible. I'd think "well, if it isn't in there, then wtf does my hash look like?" and instead of `puts h[:shares]` I'd stick a `p h` in there, which will print out an inspected version of the array. At that point, I'd see the data exists, and know the problem must be how I'm pulling it out. Also, I don't think `h.each_pair { |n,v| h[n] = v }` does anything, you are asking it for each key and value that it has, then telling it to set that key to that value. Well, if it gave you that pair, then it is already set. --0016e64f47cec3def40499ff86c4--