From: Rolf Pedersen Date: 2010-04-25T07:03:04+09:00 Subject: Re: Metaprogramming - Array initialization --0016e6470d9aa7f822048502a780 Content-Type: text/plain; charset=ISO-8859-1 Agree with Joel. Use the block form of the new method, or you'll get multiple references to the same object. This piece of code I believe does the trick. (No fault handling included, and probably not the most elegant, perhaps since I'm quite new to Ruby.) def make_array(*a) a.flatten! if a.size > 1 Array.new(a.shift){make_array(a)} elsif a.size == 1 Array.new(a.shift) end end irb(main):052:0> make_array(1, 3, 2, 1) => [[[[nil], [nil]], [[nil], [nil]], [[nil], [nil]]]] Best regards, Rolf On Sat, Apr 24, 2010 at 11:48 PM, Joel VanderWerf wrote: > Paul A. wrote: > >> Hi, >> >> In Ruby, we can declare array as explain in the doc: >> http://ruby-doc.org/core/classes/Array.html#M002150 >> >> That makes possible many kind of use, such as: >> >>> Array.new(1, Array.new(3, Array.new(2, Array.new(1)))) >>>> >>> => [[[[nil], [nil]], [[nil], [nil]], [[nil], [nil]]]] >> >> For my needs, I would like to use a code that declare an array of any >> arrays that we want. I don't know if it is possible. >> > > The above is probably not what you want. Look: > > >> a=Array.new(3, Array.new(2)) > => [[nil, nil], [nil, nil], [nil, nil]] > >> a[0][1] = 6 > => 6 > >> a > => [[nil, 6], [nil, 6], [nil, 6]] > > Try using the block form: > > >> a=Array.new(3) {Array.new(2)} > => [[nil, nil], [nil, nil], [nil, nil]] > >> a[0][1] = 6 > => 6 > >> a > => [[nil, 6], [nil, nil], [nil, nil]] > > --0016e6470d9aa7f822048502a780--