嵌套循环内变量的范围

scope of a variable inside of a nested loop

我正在尝试通读 ActiveStorage::Attached::One 对象,该对象是用户上传的 txt 文件。

谁能帮我看看为什么 line.chars.each_with_index 里面的变量 'grid' 是 nil?


txt_file = self.file.download.delete(' ')  # returns the content of the file as a string

txt_file.each_line.with_index do |line, row_index| 
  next line if row_index == 0

  if row_index == 1
    grid = self.grids.create(generation: 0, rows: line[0].to_i, cols: line[1].to_i)
  end

  line.chars.each_with_index do |cell, column_index|
    grid.cells.create(alive: cell == "*", row_position: row_index, column_position: column_index)
  end
end

非常感谢

只要 row_index 不等于 0 或不等于 1grid 就不会被赋值,因此计算结果为 nil。换句话说,只要 txt_fle 有三行或更多行,grid 就会在某个时刻变成 nil