Question on Advanced Debugging Problem Set

I was wondering what the difference between

result = Array.new(matrix[0].length, [])

and

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 = Array.new(matrix[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
end
end
result
end

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.

2 Likes

Awesome thanks Erika!