From: Robert Klemme Date: 2011-03-24T17:05:26+09:00 Subject: Re: iteration question On Thu, Mar 24, 2011 at 2:20 AM, bbiker wrote: > 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] } Even simpler irb(main):001:0> data = Array.new(5) {|i| [i]} => [[0], [1], [2], [3], [4]] irb(main):002:0> data = Array.new(5) {|*a| a} => [[0], [1], [2], [3], [4]] irb(main):003:0> data = 5.times.map {|i| [i]} => [[0], [1], [2], [3], [4]] Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/