From: Joel VanderWerf Date: 2010-07-26T10:16:25+09:00 Subject: Re: building an array of hash tables. Ted Flethuseo wrote: > I know how to build a hash table. > > frequencies = Hash.new(0) > arr = line.split(',') > frequencies[arr[0]] += 1 > > and I know how to build an array > myArr = Array.new > > but I want to know how to build an array of hash tables, as I need to > keep a set of > hash-tables sepparated, each one corresponding to an index of an array > that is split. > > Any help appreciated. > Ted. Here's a typical ruby idiom for doing that: a = [] i = 3 s = "foo" a[i] ||= Hash.new(0) a[i][s] += 1 i = 7 s = "bar" a[i] ||= Hash.new(0) a[i][s] += 1 i = 3 s = "foo" a[i] ||= Hash.new(0) a[i][s] += 1 p a # ==> [nil, nil, nil, {"foo"=>2}, nil, nil, nil, {"bar"=>1}] You can wrap that up in a class if you like: class Counter def initialize @a = [] end def count index, obj h = @a[index] ||= Hash.new(0) h[obj] += 1 end end