Ruby在类即时中错误的参数数量

Mar*_*her -2 ruby class object

我试图在Ruby中制作战舰游戏,但是当我尝试创建游戏板的实例时,我得到"错误的参数数量,0表示1".我不知道我哪里出错了,因为初始化定义明确接受了参数.

class Board

  attr_reader :grid, :default_grid

  def intitalize(grid = self.class.default_grid, random = false)
    @grid = grid
    make_random_board if random
  end

  def self.default_grid
    grid = Array.new(10){Array.new(10)}
  end

  def count
    grid.flatten.count{|x| x == :s}
  end

  def self.random
    self.new(self.default_grid, true)
  end

  def empty?(position = nil)
    return true if position.nil?
    else
    false
  end

  def full?
    grid.flatten.none?(&:nil?)
  end

  def place_random_ship
      if full? 
        raise "error, board is full"
      end

      space = [rand(grid.length),rand(grid.length)] 
        until empty?(space)
          space = [rand(grid.length),rand(grid.length)]
        end
      self[space] = :s
  end

  def make_random_board(count = 10)
    count.times do
      place_random_ship
    end
  end

end

emptygrid = Array.new(2){Array.new(2)}
myGame = Board.new(emptygrid)
Run Code Online (Sandbox Code Playgroud)

Alf*_*fie 6

您的代码中有拼写错误.你应该使用initialize而不是intitalize

我相信你可能会遇到的错误 ArgumentError: wrong number of arguments (1 for 0)

这是因为你的拼写错误,使用了默认的类initialize方法,它没有接受任何参数.

和我在你的代码中注意到的无关的东西.您已定义一个名为的方法count并使用名为的变量count.这是代码味道,我建议不同地命名方法,因为在线下,这可能会导致一些错误,您可能会发现难以调试.