【问题标题】:Undefined method << for NilClassNilClass 的未定义方法 <<
【发布时间】:2016-05-06 05:42:26
【问题描述】:

我正在尝试编写转置方法,但它不适合我。代码如下:

def my_transpose(array)
  new_matrix= Array.new
  v_entries= 0
  h_entries= 0

while v_entries < array.length 
  while h_entries < array.length 
    new_matrix[h_entries] << ([array[h_entries][v_entries]])
    h_entries +=1
  end
  v_entries +=1
  h_entries= 0
end
new_matrix
end

array = [[1,2,3], [4,5,6], [7,8,9]]

我正在尝试让 my_transpose(array) 给我:

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

我尝试添加

new_matrix[h_entries] << ([array[h_entries][v_entries]]) 

但我得到一个错误

"nil:NilClass 的未定义方法`

任何见解都会很棒。

【问题讨论】:

    标签: arrays ruby


    【解决方案1】:

    在您的第一个循环迭代中,new_matrix[h_entries] 将是 nil。所以,你不能在上面使用&lt;&lt; 方法。

    如果是nil,尝试初始化为空数组:

    new_matrix[h_entries] ||= []
    new_matrix[h_entries] << ([array[h_entries][v_entries]])
    

    【讨论】:

      猜你喜欢
      • 2021-10-25
      • 2014-06-01
      • 2015-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多