From: Stuart Clarke Date: 2008-12-18T23:50:11+09:00 Subject: Re: Using ruby hash on array Sorry for not being clear. I am actually parsing data from Windows event logs and as a result the data is held in structured fields. Earlier in my program I load the contents of a number of event logs into an array and then ready the data using structs for example to read the ID number - event.event_id more complicated for descriptions - event.description[/Name:\t(.+?)\r\n/, 1]} So what I would like to do is read my event log array and check for specific event ID's (if event.event_id == 100). If the if statement finds the ID 100 it reads name from event.description. Everything mention thus far is working correctly. When this is complete I then want to do a count on how many times each name occurs e.g. bob = 2, sue = 12. My thoughts were to load the event.description[/name:/] into a hash and then do a count on each name in the hash and print it out. Does this make more sense?? Robert Klemme wrote: > 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. > >> 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 -- Posted via http://www.ruby-forum.com/.