Home > Mobile >  scope of a variable inside of a nested loop
scope of a variable inside of a nested loop

Time:05-09

I am trying to read through an ActiveStorage::Attached::One object that is a txt file uploaded by the user.

Could anyone help me why the variable 'grid' inside the line.chars.each_with_index is 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

thanks a lot

CodePudding user response:

Whenever row_index is not equal to 0 or equal to 1, grid is not assigned and therefore evaluates to nil. In other words, whenever txt_fle has three lines or more, grid will be nil at some point.

  • Related