From: "Jesús Gabriel y Galán" Date: 2011-05-25T19:32:26+09:00 Subject: Re: 2d array of hashes On Wed, May 25, 2011 at 12:23 PM, Alex Raduca wrote: > Hi, > > I am trying to solve the Sudoku Ruby Quiz using a 2d array of hashes > data model but I probably keep doing something wrong since the hashes > are referenced at row level(last row of the sudoku matrix is > referenced). > > Could I get a hint on where I should insert the Hash.new when dealing > with 2d arrays. I have googled it but I could only find simple array of > hashes examples. So, what is the data model you want? A different hash for each cell? Then there is a problem here: > # creates sudoku matrix and fills it in with data > sudoku=Array.new(9,Array.new(9)) This creates an array of size 9, pointing 9 times to the same array. Check it: ruby-1.8.7-p334 :001 > a = Array.new(9, Array.new(9)) ruby-1.8.7-p334 :002 > a[0].object_id => -611740938 ruby-1.8.7-p334 :003 > a[1].object_id => -611740938 So, if you add a hash to that inner array, all your rows will have the same hash. Try this: sudoku = Array.new(9) { Array.new(9)} or if you want to assign an empty hash right away: sudoku = Array.new(9) { Array.new(9) {{}}} now, each position in the array of arrays has its own independent hash: ruby-1.8.7-p334 :003 > sudoku[0][0][:possibilities] = [1,2,3,4,5,6,7,8,9] => [1, 2, 3, 4, 5, 6, 7, 8, 9] ruby-1.8.7-p334 :004 > sudoku => [[{:possibilities=>[1, 2, 3, 4, 5, 6, 7, 8, 9]}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}]] Jesus.