From: Robert Klemme Date: 2003-10-01T16:40:10+09:00 Subject: Re: Array and hash iteration questions "Ben Giddings" schrieb im Newsbeitrag news:3F79D516.9050509@infofiend.com... > I have a CSV file and I'm trying to do a few things with it. Essentially > what it boils down to is: count the number of times a certain value is > seen, then count the number of times another value is seen in conjunction > with the first one. > > I'm iterating over the lines of the file, and splitting them into an array > with arr = line.split(/,/). That part works well, but there are a few > questions about how to do something efficiently. > > In order to count the number of times something is seen, I took the approach: > > cases = Hash.new(0) > .. > cases[arr[324]] += 1 > .. > > But now I want to save the number of cases where another value occurs with > the first one. (Essentially errors indexed by case) > > The approach I have now is: > > cases = Hash.new(0) > errors = Hash.new(0) > .. > case = arr[324] > cases[case] += 1 > if arr[532] =~ /Error/ > errors[case] += 1 > end > .. > > That works, but it seems to me that I really should be doing this with one > hash, not two. Any suggestions? cases = Hash.new {|h,k| h[k] = [0, 0]} ... ca = arr[324] counter = cases[ca] counter[0] += 1 counter[1] += 1 if /Error/ =~ arr[532] > Next, I want to print out the values. It is easy to do this with > cases.each, but I'd like to print them out, sorted by case. The best > solution I have so far uses cases.keys.sort.each, then inside the block > uses cases[key] (and errors[key]). cases.sort.each do |ca, counter| printf "%10s: %4d", ca, counter[0] printf " %4d", counter[1] if counter[1] > 0 print "\n" end Regards robert