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