From: Martin DeMello Date: 2009-02-16T19:57:25+09:00 Subject: Re: How to do this complicated logic in ruby On Mon, Feb 16, 2009 at 3:30 PM, Valentino Lun wrote: > Dear all > > I have an array with size around 1000, I want to perform some data > checking and correction in this array. > > For instance, the first record of this array is a hash, as follow > my_array[0] = {"server"=>"AHN", "hosp"=>"AHN", "loc"=>"PC1", > "pspec"=>"ANA", "number"=>"1", "pcat"=>"1"} > > server hosp loc pspec pcat > AHN AHN PC1 ANA 1 > PWH AHN PC1 ANA 1 > NDH AHN PC1 ANA 2 <= This pcat value need update in > array1 > TMH AHN PC1 ANA 2 <= This pcat value need update in > array1 > ....... > ..... > ... > (around 1000 records) > > When keys hosp, loc, pspec has the same values, their pcat must be > identical. So, there is problem in the last two records, the key pcat > should be 1, because the pcat is correct if array["server"] equal to > array["hosp"]. Simple way: 1. Have a 'signature' for each row, composed of the hosp, loc and pspec. Could be as simple as def signature(ary, row) %w(hosp loc pspec).map {|k| ary[row][k]}.join(",") end 2. Collect all the rows with the same signature verify = Hash.new {|h,k| h[k] = []} ary.each_with_index {|row, i| h[signature(ary, row)] << [i, row['pcat']] } 3. See if there are any problems verify.each_pair {|k, v| if v.length > 1 fix_array_for(v) end } 4. Write fix_array_for(v) Note that v is an array of pairs of [index, pcat]. So for your example, it would be [[0,1], [1,1], [2,2], [3,2]] you basically need to iterate over that array, see which pcat is right, then iterate over it once more and set all the pcats to the right value. There are probably more efficient ways to do all this, but this has the advantage of being straightforward. martin