building an array of hash tables.

T

Ted Flethuseo

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.
 
J

Joel VanderWerf

Ted said:
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 ||= Hash.new(0)
a += 1

i = 7
s = "bar"
a ||= Hash.new(0)
a += 1

i = 3
s = "foo"
a ||= Hash.new(0)
a += 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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top