From: yermej Date: 2008-01-24T23:59:58+09:00 Subject: Re: Change a data structure On Jan 24, 2:14 am, Michael Schmarck wrote: > Hello! > > I've got the following data structure, which I need to change, to > suit further needs: > > timing_given = { > "Performance Test of Item Access using Lists" => [ > {"Plants" => 100, "Customers" => 50, "Total" => 150}, > {"Plants" => 85, "Customers" => 60, "Total" => 140}, > {"Plants" => 111, "Customers" => 77, "Total" => 188} > ], > "Performance Test of Item Access using Advance Item Search" => [ > {"Work List" => 17, "Total" => 42}, > {"Work List" => 10, "Total" => 50}, > {"Work List" => 22, "Total" => 99}, > {"Work List" => 15, "Total" => 60} > ] > > } > > Now I'd like to change that, so that it looks somewhat like this: > > timing_wanted = { > "Performance Test of Item Access using Lists" => { > "Plants" => [100, 85, 111], "Customers" => [50, 60, 77], "Total" => [150, 140, 188] > }, > Performance Test of Item Access using Advance Item Search" => { > "Work List" => [17, 10, 22], "Bookmarks" => [30, 33, 27], "Total" => [42, 50, 99] > } > > } > > Let me explain... > > I've got a hash called "timing_given", which has, right now, two keys. > These keys have arrays as values. The elements of these arrays are again > hashes. > > Now this should be changed to match what's shown in "timing_wanted". Ie., > create a hash, which has two keys. These keys should have hashes as values > and the values of these hashes should be arrays. > > The data represent some timing measurement data. In the example I'm showing, > the Plants, Customers and Total tests have been run 3 times, consecutively. > So, first the Plants test was run, then the Customers test and then the > Total test. > > I want to collect all the Plants (etc.pp.) tests in one array. This array > should have as many elements, as there were test runs for the Plants test. > Accordingly for the other tests. > > In reality, there are more tests than what I've shown. And as you can see, > there are two test "categories", called "Performance Test of Item Access > using Lists" and "Performance Test of Item Access using Advance Item Search". > In reality, there might be more. Under these categories, there might be > 2, 3, 4 or whatever test runs - but the number of test runs for a category > is always constant. > > How would I best "mess up" that timing_given data structure, so that it > resembles the timing_wanted structure? > > Thanks a lot, > Michael I'll offer up an inject version (mostly for novelty's sake): timing_given.each {|k, v| timing_given[k] = v.inject(Hash.new {|h, k| h[k] = []}) {|acc, h| h.each {|k, v| acc[k] << v}; acc}}