bleedr
bleedr

Reputation: 25

Create an array filled with separate hashes

I'm trying to create an array in which every entry should be a separate, identical hash entry in the beginning.

iTabSize = 500 #protein max lenght
arrTable = Array.new(iTabSize) 
hshTable = {"-"=>0,"B"=>0,"Z"=>0,"I"=>0,"M"=>0,"T"=>0,"N"=>0,"K"=>0,"S"=>0,"R"=>0,"V"=>0,"A"=>0,"D"=>0,"E"=>0,"G"=>0,"F"=>0,"L"=>0,"Y"=>0,"X"=>0,"C"=>0,"W"=>0,"P"=>0,"H"=>0,"Q"=>0}
0.upto(iTabSize){|x| arrTable[x]= hshTable}

The problem is if I change the hash in one entry of the array, the hash gets updated for all other entries :/

arrTable[x][strSeq[x]] = arrTable[x][strSeq[x]] + 1

strSeq is a sequence containing letters from the hash. The result is that each x of arrTable contains exactly the same values?

Am I doing something wrong when creating the array with hashes?

I tried with

arrTable = Array.new {Hash.new}
arrTable[x] = Array.new

but it doesn't change a thing! Tnx!

Upvotes: 0

Views: 55

Answers (1)

spickermann
spickermann

Reputation: 106802

I think this should work for you:

max_protein = 500
hash_table  = {"-"=>0,"B"=>0,"Z"=>0,"I"=>0,"M"=>0,"T"=>0,"N"=>0,"K"=>0,"S"=>0,"R"=>0,"V"=>0,"A"=>0,"D"=>0,"E"=>0,"G"=>0,"F"=>0,"L"=>0,"Y"=>0,"X"=>0,"C"=>0,"W"=>0,"P"=>0,"H"=>0,"Q"=>0}

array_table = Array.new(max_protein) { hash_table.clone }

Upvotes: 4

Related Questions