# Building an array of hash tables

**URL:** <https://www.ruby-forum.com/t/building-an-array-of-hash-tables/192192>\
**Category:** Ruby\
**Created:** [July 26, 2010, 1:51am UTC](https://www.ruby-forum.com/t/building-an-array-of-hash-tables/192192 "2010-07-26T01:51:14Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![tedforte](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/ecb155/32.png) [@tedforte](https://www.ruby-forum.com/u/tedforte)\
**Post date:** [July 26, 2010, 1:51am UTC](https://www.ruby-forum.com/t/building-an-array-of-hash-tables/192192/1 "2010-07-26T01:51:14Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![tedforte](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/ecb155/32.png) [@tedforte](https://www.ruby-forum.com/u/tedforte)\
**Post date:** [July 26, 2010, 3:17am UTC](https://www.ruby-forum.com/t/building-an-array-of-hash-tables/192192/2 "2010-07-26T03:17:17Z")

</div>

Ted F. wrote:

> 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
