Hashes

hopefully someone might be able to shed some light on this.

I have a ruby test application which I’m fetching data from a
database. I want to store the results into a hash based on the
following principle;

loop through the rows
does the hash contain a key value as read from that row
if it does then place the row into an array and then add it to an
array of rows which might already be within the hash
if the hash doesn’t contain the key then create a key and add the
row to an array an append it to the hash

unfortunately i’m relatively new to Ruby and can’t figure out how to
do this. In a few simply tests I declare a variable called

a = []

when I loop over the returned database rows using row, I assign row
into a

a += row

this works but rather than the array being a length of the total
number of rows, it’s actually the length of all the rows multiplied by
the number of columns. I guess the first problem is getting the rows
into a correct array. Once this is done I should be able to say

“hash, have you got a key with the value 1” - the hash might say “yes,
and here is an array of rows.” I’ll take that array of rows and add
another row to it and save back to the hash.

can anyone help?

hopefully someone might be able to shed some light on this.
loop through the rows
does the hash contain a key value as read from that row
if it does then place the row into an array and then add it to an
array of rows which might already be within the hash
if the hash doesn’t contain the key then create a key and add the
row to an array an append it to the hash

I assume that you can already do the database lookup etc.
If you are then iterating over the rows, try the following:

h = Hash.new {|hash,key| hash[key] = []}
while(row = …) #collect each row
key = row[0]
h[key] << row
end

This creates a hash where the value of a newly created entry is always
an
array.
Therefore, you no longer need to check if the hash has the key or not,
you
can simply append to the array based on the key.

Andrew T.
[email protected]
082 415 8283
skype: andrewtimberlake

“I have never let my schooling interfere with my education.”
–Mark Twain

On Jan 15, 1:04 pm, Andrew T. [email protected]
wrote:

Andrew T.
[email protected]
082 415 8283
skype: andrewtimberlake

“I have never let my schooling interfere with my education.”
–Mark Twain

thanks very much for that - i’ll give it go