From: Valentino Lun Date: 2009-02-17T18:00:45+09:00 Subject: Re: How to do this complicated logic in ruby Dear all Thank you for your help. Finally, I used about 5 hours (>_<) to figure out my solution and it works..But it takes long time to execute. Below is my code to share with you all, and I am seeking your expert advices if any optimization can be done. Thank you. # data collection about 5000 records for each variable (lis, gcrs) lis = ActiveRecord::Base.connection.execute("select * from lis_requests order by hosp, spec, loc, pspec") gcrs = ActiveRecord::Base.connection.execute("select * from gcrs_requests order by hosp, spec, loc, pspec") def find_correct_pcat(arr) server_ref = {"AHN" => "AHN", "TPH" => "AHN", "NDH" => "NDH", "BBH" => "NDH", "CHS" => "NDH", "PWH" => "PWH", "SH" => "PWH"} arr.each do |x| return x["pcat"] if x["server"] == server_ref[x["hosp"]] end #if not, then find the pcat with the largest "number" a.sort_by {|y| y["number"].to_i}.last["pcat"] end # The result will put in this hash result = {} #looping in all index key and get the result. lis.collect {|x| [x["hosp"],x["spec"],x["loc"],x["pspec"]]}.uniq.each do |index_key| lis_record = lis.select {|x| x["hosp"] == index_key[0] and x["spec"] == index_key[1] and x["loc"] == index_key[2] and x["pspec"] == index_key[3]} gcrs_record = gcrs.select {|x| x["hosp"] == index_key[0] and x["spec"] == index_key[1] and x["loc"] == index_key[2] and x["pspec"] == index_key[3]} lis_req_count = lis_record.inject(0) {|sum,n| sum + n["number"].to_i } gcrs_req_count = gcrs_record.inject(0) {|sum,n| sum + n["number"].to_i } if lis_record.collect {|x| x["pcat"]}.uniq.size == 1 pcat = lis_record.first["pcat"] else pcat = find_correct_pcat(lis_record) end result[index_key] = [pcat, gcrs_req_count, lis_req_count] end Thanks again Valentino -- Posted via http://www.ruby-forum.com/.