尝试使用字符串插值时获取 nil:NilClass 的未定义方法 []

Getting undefined method [] for nil:NilClass when trying to use string interpolation

我是一般编码的新手,刚开始 Ruby。我正在使用 Odin 项目,我们必须创建一个井字游戏。我正在尝试显示板,但在以下代码中,我不断收到 undefined method [] for nil:NilClass 错误:

class Board
  attr_reader :display_board, :check_board

  def initialize
    @board = %w[1 2 3 4 5 6 7 8 9]
  end

  class << self
    attr_reader :board
  end

  def self.display_board
    puts '|-----------|'
    puts "| #{@board[0]} | #{@board[1]} | #{@board[2]} |" # error occurs on this line
    puts '|---+---+---|'
    puts "| #{@board[3]} | #{@board[4]} | #{@board[5]} |"
    puts '|---+---+---|'
    puts "| #{@board[6]} | #{@board[7]} | #{@board[8]} |"
    puts '|-----------|'
  end

我让它在某个时候工作,但我不知道我做了什么破坏了它。有什么提示吗?

两种表达方式: 1.

    class Board
      def self.board
        %w[1 2 3 4 5 6 7 8 9]
      end

      def self.display_board
  
        puts '|-----------|'
        puts "| #{Board.board[0]} | #{Board.board[1]} | #{Board.board[2]} |" 
          # error occurs on this line
        puts '|---+---+---|'
        puts "| #{Board.board[3]} | #{Board.board[4]} | #{Board.board[5]} |"
        puts '|---+---+---|'
        puts "| #{Board.board[6]} | #{Board.board[7]} | #{Board.board[8]} |"
        puts '|-----------|'

       end

   p Board.display_board #access class methods directly
  1. 还有一个是这样的:

     class Board2
    
        attr_reader :board
    
        def initialize
            @board = %w[1 2 3 4 5 6 7 8 9]
        end
    
        def display_board
           puts '|-----------|'
          puts "| #{board[0]} | #{board[1]} | #{board[2]} |" # error occurs on this line
          puts '|---+---+---|'
          puts "| #{board[3]} | #{board[4]} | #{board[5]} |"
          puts '|---+---+---|'
          puts "| #{board[6]} | #{board[7]} | #{board[8]} |"
         end
        end
    
       board = Board2.new #create Board2 object
       p board.display_board #access public methods