Eric Jacoboni
11/8/2006 4:02:00 PM
Friedrich Dominicus <just-for-news-frido@q-software-solutions.de>
writes:
> 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]]
> 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?
I think so... see ri Array.new
In your first test, all array items refer to the same
default obj. If it happens to be modified, this modification affects all the
element that refer to this default object.
In you second test, the block create a new copy for each
element. Modifying one of them, doesn't affect the others.
--