From: bbiker Date: 2011-03-24T10:20:29+09:00 Subject: Re: iteration question On Mar 23, 7:20 pm, Rimantas Liubertas wrote: > data = Array.new(5,[]) > This gives you array with five references to the same array object: > > ruby-1.9.2-p0 :036 > data = Array.new(5,[]) > => [[], [], [], [], []] > > ruby-1.9.2-p0 :037 > data[0].object_id > => 2156232780 > ruby-1.9.2-p0 :038 > data[1].object_id > => 2156232780 > > > 0.upto(4) do |i| > > data[i].push(i) > > no matter where you push you are still pushing to the same single array > > What you want probably is: > > data = Array.new(5) {[]} > 0.upto(4) do |i| > data[i].push(i) > end > p data > > In this case it is the same as > > data = Array.new(5) {|index| [index]} > => [[0], [1], [2], [3], [4]] > > Regards, > Rimantas > --http://rimantas.com/ Alternate way of doing the same thing: data = [] 0.upto(4) { |i| data << [i] } regards, bbiker