0

What is going on in the Array initialization that's causing the disparity in int assignment?

arr = Array.new(3) { Array.new(3) { Array.new(3) } }
3.times do |x|
  3.times do |y|
    3.times do |z|
      arr[x][y][z] = Random.rand(1..9)
    end
  end
end
puts arr.to_s
#=> [[[3, 3, 1], [4, 9, 6], [2, 4, 7]], [[1, 6, 8], [9, 8, 5], [1, 7, 5]], [[2, 5, 9], [2, 8, 8], [9, 1, 8]]]
#=> [[[2, 4, 4], [6, 8, 9], [6, 2, 7]], [[2, 7, 7], [2, 1, 1], [8, 7, 7]], [[5, 3, 5], [3, 8, 1], [7, 6, 6]]]
#=> [[[4, 9, 1], [1, 6, 8], [9, 2, 5]], [[3, 7, 1], [7, 5, 4], [9, 9, 9]], [[6, 8, 2], [8, 2, 8], [2, 9, 9]]]

arr = Array.new(3, Array.new(3, Array.new(3)))
3.times do |x|
  3.times do |y|
    3.times do |z|
      arr[x][y][z] = Random.rand(1..9)
    end
  end
end
puts arr.to_s
#=> [[[8, 2, 4], [8, 2, 4], [8, 2, 4]], [[8, 2, 4], [8, 2, 4], [8, 2, 4]], [[8, 2, 4], [8, 2, 4], [8, 2, 4]]]
#=> [[[2, 1, 4], [2, 1, 4], [2, 1, 4]], [[2, 1, 4], [2, 1, 4], [2, 1, 4]], [[2, 1, 4], [2, 1, 4], [2, 1, 4]]]
#=> [[[2, 7, 6], [2, 7, 6], [2, 7, 6]], [[2, 7, 6], [2, 7, 6], [2, 7, 6]], [[2, 7, 6], [2, 7, 6], [2, 7, 6]]]
wurde
  • 2,487
  • 2
  • 20
  • 39
  • You can create the array like this: `arr = Array.new(3) {Array.new(3).map {Array.new(3,v)}}`, where `v`, if present, is the default value for all 27 elements of `arr`. If you set `arr[0][0][0] = 'cat'`, you will find that that is the only element that has changed. If your array had more dimensions than three, you'd probably want to construct it using recursion. – Cary Swoveland Apr 09 '14 at 04:27

1 Answers1

1

When you use new(size=0, obj=nil) to initialize the array:

From the doc:

In the first form, if no arguments are sent, the new array will be empty. When a size and an optional obj are sent, an array is created with size copies of obj. Take notice that all elements will reference the same object obj.

If you want multiple copy, then you should use the block version which uses the result of that block each time an element of the array needs to be initialized.

xdazz
  • 158,678
  • 38
  • 247
  • 274