From: Robert Klemme Date: 2008-12-18T17:34:06+09:00 Subject: Re: Using ruby hash on array 2008/12/17 Stuart Clarke : > I would like to process some data from an array and using hash to > perform a count on one aspect of the data in the array. The array holds > lines of similarly formatted data like so > > data A data B data C data D data E data F > data A data B data C data D data E data F > data A data B data C data D data E data F You do not say whether the format is delimited or fixed width. > data A is the identifier of each row full of data, data F contains a lot > of data which requires a regular expression which is passed to a method > for example: > > "#{data F[/Name:\t(.+?)\r\n/, 1]}" > > I am stuck writing the hash section of the code. The alogorithm is > > if data A == 100 > load data F reg expression into hash > end > count data F to determine the number of each name extracted by the > regular expression > print bob 6, sue 12, tim 1 A framework: Data = Struct.new :a, :b:, :c, :d, :e, :f def Data.parse(line) d = new(*line.strip.split(/\s+/)) d.f = Integer(d.f) d end count = Hash.new 0 ARGF.each do |line| data = Data.parse(line) count[data.f[/Name:\t(.+?)\r\n/, 1]] += 1 if data.a == 100 end count.each do |a, cnt| printf "%20s %6d\n", a, cnt end Kind regards robert -- remember.guy do |as, often| as.you_can - without end