From: Todd Benson Date: 2007-07-12T07:04:38+09:00 Subject: Re: Accessing a specific index in a nested array On 7/11/07, Pieter Mans wrote: > Florian Gross wrote: > >> For example, this works: > >> irb> array[2] > >> => [2, 2, 2, 2, 2, 2, 2, 2, 2, 2] > >> > >> But this doesn't seem to: > >> irb> array[2[2]] > >> => [2, 2, 2, 2, 2, 2, 2, 2, 2, 2] > >> > >> I'm pretty sure I'm just getting the syntax wrong. > > > > Yup, you're calling [] on the number 2. You want array[2][2]. > > Thanks! That worked nicely. I'm getting a weird problem when setting > values tho. When I try to set the value of an item in a nested array, it > sets the value in all the other nested arrays too: > > irb> test = Map.new(5,5) > => # "#", "#"], ["#", "#", "#", "#", "#"], ["#", "#", "#", "#", "#"], ["#" > , "#", "#", "#", "#"]]> > irb> test.coords[1][1] = 0 > => 0 > irb> test.coords > => [["#", 0, "#", "#", "#"], ["#", 0, "#", "#", "#"], ["#", 0, "#", "#", > "#"], ["#", 0, "#", "#", "#"], ["#", 0, "#", "#", "#"]] > > Any idea what I'm doing wrong? Most likely you have the same object for each element of your outside array. You can check by doing this: irb> test.coords[0] === test.coords[1] #for you, this will probably return true => true Look at how your array is created. There are a number of ways to do it. Here's one that's not sexy but works. size = 5 test.coords = [] size.times { test.coords << Array.new size } hth, Todd