Question on Advanced Debugging Problem Set

I was wondering what the difference between

result =[0].length, [])


result = []
matrix[0].length.times {result << []}

For the transpose question in the advanced debugging problems, I was able to make the method work with the second string of code, but couldn’t figure out why the first one doesn’t work for the problem. Here is the code for that problem:

Write a method that will transpose a rectangular matrix (array of arrays)

def transpose(matrix)
#result =[0].length, []) #HARD - PASS BY REFERENCE ISSUE
result = []
matrix[0].length.times {result << []}
matrix.each do |row|
row.each_with_index do |el, col_idx|
result[col_idx] << el

Hi Nathan,

When you create an Array with the method in the given problem, the value for all array elements is being set to [] . That same object will be used for the value of all array elements, so each time you change it, all values contained in that array will change to that new value. See the ruby documentation below:

Hope this helps.


Awesome thanks Erika!