使用 "each" 方法为二维数组赋值

Assigning values to a 2D array using "each" method

我正在尝试转置 [[0, 1, 2], [3, 4, 5], [6, 7, 8]]。我得到 [[2, 5, 8], [2, 5, 8], [2, 5, 8]].

我可以看到 p transposed_arr 行发生了什么,但不明白为什么会这样。在每次迭代中,它都会更改每一行,而不是仅更改一行。

def my_transpose(arr)
  # number of rows
  m = arr.count

  #number of columns
  n = arr[0].count

  transposed_arr = Array.new(n, Array.new(m))

  # loop through the rows
  arr.each_with_index do |row, index1|

      # loop through the colons of one row
      row.each_with_index do |num, index2|

          # swap indexes to transpose the initial array
          transposed_arr[index2][index1] = num
          p transposed_arr
      end
  end
  transposed_arr
end

您只需稍作改动,您的方法就可以正常工作。替换:

transposed_arr = Array.new(n, Array.new(m))

与:

transposed_arr = Array.new(n) { Array.new(m) }

前者使 transposed_arr[i] 对所有 i 相同的对象(大小为 m 的数组)。后者为每个 i

创建一个大小为 m 的单独数组

案例一:

transposed_arr = Array.new(2, Array.new(2))
transposed_arr[0].object_id
  #=> 70235487747860 
transposed_arr[1].object_id
  #=> 70235487747860

案例二:

transposed_arr = Array.new(2) { Array.new(2) }
transposed_arr[0].object_id
  #=> 70235478805680 
transposed_arr[1].object_id
  #=> 70235478805660

改变你的方法 returns:

[[0, 1, 2],
 [3, 4, 5],
 [6, 7, 8]]