1 Replies - 967 Views - Last Post: 06 February 2014 - 05:07 PM Rate Topic: -----

#1 heaphyg  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 85
  • Joined: 30-August 13

What is with this output?

Posted 06 February 2014 - 03:38 PM

Why are all the sub arrays being changed. I would expect only the 3rd sub array to be changed..

2.0.0p353 :037 >   arr = Array.new(4, Array.new(4, 0))
 => [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] 
2.0.0p353 :038 > arr[2][1] = 1
 => 1 
2.0.0p353 :039 > arr
 => [[0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0]] 


This post has been edited by heaphyg: 06 February 2014 - 03:38 PM


Is This A Good Question/Topic? 0
  • +

Replies To: What is with this output?

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2118
  • View blog
  • Posts: 3,244
  • Joined: 21-June 11

Re: What is with this output?

Posted 06 February 2014 - 05:07 PM

What Array.new(n, x) does is that it creates an n-element array and then assigns x to each spot in the array. Notably it does not call dup or clone on x. Also since it's just a method argument, x isn't evaluated more than once. So in your case you end up with an array that contains 4 references to the same subarray.

To avoid this, you can use the block version of Array.new, which does evaluate the contents of the block multiple times. So that'd be:

Array.new(4) do
  Array.new(4,0)
end

Was This Post Helpful? 2
  • +
  • -

Page 1 of 1