From: "Simon Kröger" Date: 2005-09-08T04:54:28+09:00 Subject: Re: weird result when updating an array element Nelson Owen wrote: > Given the code below, only one element in @ver should be changed, > however when I execute the code all the elements are changed. Can anyone > explain why this is happening? > > class SomeClass > def initialize > @ver = Array.new(2, {'pos' => Array.new(3), 'col' => Array.new(4)}) > @ver[0]['pos'][0] = 0 > puts @ver.inspect > end > end > SomeClass.new > > actual result: > [{"col"=>[nil, nil, nil, nil], "pos"=>[0, nil, nil]}, {"col"=>[nil, nil, > nil, nil], "pos"=>[0, nil, nil]}] > > expected result: > [{"col"=>[nil, nil, nil, nil], "pos"=>[0, nil, nil]}, {"col"=>[nil, nil, > nil, nil], "pos"=>[nil, nil, nil]}] > > from the Array docs: ...it is created with size copies of obj (that is, size references to the same obj). So ver[0] and ver[1] are in fact pointing to the same object. You can use: @ver = Array.new(2) {{'pos' => Array.new(3), 'col' => Array.new(4)}} wich looks odd, but works :) cheers Simon