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]]]
1
  • 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. Commented Apr 9, 2014 at 4:27

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.