Will Ashley Will Ashley - 7 months ago 20
Ruby Question

Ruby wrong number of arguments in class instantitation

I am trying to make a battleship game in Ruby, but when I try to create an instance of the game board, I get "wrong number of arguments, 0 for 1". I dont see where I am going wrong as the initialize definition clearly accepts arguments.

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)

Answer

You have a typo in your code. You should be using initialize instead of intitalize

And i believe the error you might have been getting would be ArgumentError: wrong number of arguments (1 for 0)

Which is because of your typo, the default class initialize method was used, which doesn't take in any arguments.

And something unrelated that i noticed in your code. You have defined a method named count and use variables named count. This is a code smell and i would suggest naming the method differently, because down the line, this might cause some bugs, that you might find hard to debug.