From: dblack@... Date: 2006-11-09T01:16:36+09:00 Subject: Re: Suprise in Ruby Hi -- On Thu, 9 Nov 2006, Friedrich Dominicus wrote: > I can not remember having read about it before, however the following > happens here: > > irb(main):015:0> arr = Array.new(3, Array.new) > [[], [], []] > irb(main):016:0> arr[0].push(1) > [1] > irb(main):017:0> arr > [[1], [1], [1]] > > ruby 1.8.5 > > but > irb(main):018:0> arr1 = Array.new(3) > [nil, nil, nil] > irb(main):019:0> 0.upto(2) {|i| arr1[i] = Array.new} > 0 > irb(main):020:0> arr1 > [[], [], []] > irb(main):021:0> arr1[0].push(1) > [1] > irb(main):022:0> arr1 > [[1], [], []] > > I'm not getting it. Is it supposed to work that way? Yes. When you do this: Array.new(n, obj) you get an array of size n, with each element initialized to obj. obj is only evaluated once, so if it's "Array.new", you get the same array for all the elements. David -- David A. Black | dblack@wobblini.net Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3] DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4] [1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com [2] http://dablog.rubypal.com | [4] http://www.rubycentral.org