From: Alex Young Date: 2007-02-16T02:35:41+09:00 Subject: Re: Iterating through 2 fields for one hash, or array. Peter Bailey wrote: > Hello, > I'm using Jamey Cribbs' KirbyBase as a database. The beauty of it is, of > course, that it's all pure Ruby. . . . > > I need to iterate through a table with multiple fields. I've shown here > a very rudimentary example of the data that I'm working with. > > Cost Center Page Count > TMUS00 64 > ER0000 32 > DER000 128 > TMUS00 32 > DER000 64 > ER0000 10 > > I want to iterate through the table and create a hash, or an array, that > includes a single entry for each cost center and the total number of > pages counted for that cost center. So, I'd like to end up with > something like this below. I'm thinking I need a hash because the cost > center would be the key, with the page count being its value. > > Cost Center Page Count > TMUS00 96 > ER0000 42 > DER000 192 I don't know the syntax for getting the data out of KirbyBase, but the trick I usually use for this sort of thing is a hash with a default value. Something like: @cost_centers = Hash.new(0) def add_to_cost_centers(center_key, amount) @cost_centers[center_key] += amount end Hope this helps, -- Alex