Ruby & # 8594; Writing to 2D Arrays

I am working on array issues outlined at http://prepwork.appacademy.io/mini-curriculum/array/

I am trying to create a function my_transpose that takes in a matrix and returns its transpose.

I am very confused about writing a 2D array! Here is a code snippet that highlights my confusion.

rows = [ [0, 1, 2], [3, 4, 5], [6, 7, 8] ] columns = Array.new(3 , Array.new(3)) puts columns.to_s #Output is a 3 x 3 array filled with nil columns[0][0] = 0 puts columns.to_s #Output is [[0,nil,nil], [0,nil,nil], [0,nil,nil]] 

Why does changing columns [0] [0] change all three variables? Shouldn't it just change the first cell in the first row?

+5
source share
2 answers
 columns = Array.new(3 , Array.new(3)) 

Here Array.new(3) is called once, and the three sub-arrays of columns actually refer to the same Array object. Check their object_id :

 columns[0].object_id # => 70296096047460 columns[1].object_id # => 70296096047460 columns[2].object_id # => 70296096047460 

To change the modification of columns[0][0] , change columns[1][0] and columns[2][0] .


Use this instead:

 columns = Array.new(3) {Array.new(3)} 
+7
source

@YuHao explained what you need:

 Array.new(3) { Array.new(3) } 

In fact, you can expand this a bit to create your own transpose method:

 def my_transpose(arr) Array.new(arr.size) { |i| Array.new(arr.size) { |j| arr[j][i] } } end my_transpose(rows) #=> [[0, 3, 6], # [1, 4, 7], # [2, 5, 8]] 

See Array :: new .

+3
source

All Articles