0

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!

2
  • spickermann gave a good answer. The problem is that arrTable[x] = hshTable is ensuring every array entry is pointing to the same object (the hash hshTable). What you want is for every entry to have a new object which is a copy of the original hash. hshTable.clone will give you a new (cloned) object from the hash table. Commented Nov 14, 2014 at 10:43
  • It's not relevant to your question, but an easy way to generate hshTable is hshTable["-", *?A..?Z].product([0]).to_h, assuming you don't care about the order of keys. Commented Nov 15, 2014 at 7:12

1 Answer 1

4

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 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.