문제

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]]]
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top