From: William James Date: 2007-02-08T07:10:09+09:00 Subject: Re: histogram of histograms On Feb 7, 2:53 pm, "Charles L. Snyder" wrote: > Hi > > I have several text files that look like this: > > Brazil, 10 > Brazil, 13 > Brazil, 9 > Bulgaria, 1 > Canada, 48 > Canada, 52 > Canada, 38 > Canada, 55 > Canada, 59 > Chile, 1 > Chile, 1 > Chile, 2 > China, 7 > China, 18 > China, 19 > China, 22 > China, 25 > > I need to iterate through the above file(s) and get the data > summarized in the form: > > Canada, 252 > China, 91 > Chile, 4 > Brazil, 32 > Bulgaria, 1 > > I know how to go from a single column list with multiple repeated > values to a 'histogram' type list, ie: > > my_hash = countries.inject(Hash.new { 0 }) { |counts, key| counts[key] > += 1; counts} > my_hash = my_hash.sort { |a,b| a[1] <=> b[1] } > > but I'm unable to figure out how to get the 2-column csv values into a > total by country as shown above. > (I do have another file "countries.txt" which is a unique list of > countries.) > > Thanks in advance! > > CLS hash = Hash.new(0) "\ Brazil, 10 Brazil, 13 Brazil, 9 Bulgaria, 1 Canada, 48 Canada, 52 Canada, 38 Canada, 55 Canada, 59 Chile, 1 Chile, 1 Chile, 2 China, 7 China, 18 China, 19 China, 22 China, 25".each{|s| s.split(',').inject{|k,v| hash[k] += v.to_i }} p hash